304 North Cardinal St.
Dorchester Center, MA 02124

# Partition Array into 3 Subarrays to maximise the product of sums

You’re given an array A[] of dimension N, the duty is to divide the array into precisely three subarrays such that each aspect belongs to precisely one subarray such that the product of the sum of the subarrays is the utmost.

Examples:

Enter: N = 4, A[] = { 1, 2, 2, 3}
Output: 18
Clarification: The optimum partitions are {1, 2}, {2}, {3}

Enter: N = 3, A[] = { 3, 5, 7}
Output: 105
Clarification: There is just one potential partition {3}, {5}, {7}.

Strategy: This drawback might be solved utilizing the idea of sliding window and prefix-suffix array.

First, calculate the utmost product of two subarrays contemplating the dimensions of the array from 0 to N ranging from proper. Now as soon as we’ve got the utmost product of two subarrays then the third subarray will likely be on the left aspect.

For instance, if we’ve got calculated the utmost product of two subarrays for all of the arrays ranging from i to N the place 0 < i < N – 1 then the third subarray will likely be subarray from 0 to i. And now we will calculate the utmost product of those two subarrays to get most product of three subarrays.

Comply with the steps talked about beneath to implement the thought.

• Create a suffix array of dimension N.
• Create two variables x and y to retailer the sum of the primary two subarrays and initialize them as A[N-2] and A[N-1].
• Initialize suff[N-1] because the product of x and y.
• Now broaden the subarray with sum x by 1 and maintain sliding the subarray with sum y in direction of the subarray with sum x till suff[i] is lower than x*y and replace suff[i] as x*y.
• Lastly, run a loop to calculate the utmost product between subarray 0 to i and the utmost product of two subarrays from i to N i.e. suff[i].

Under is the implementation of the above strategy:

## C++

 `#embody ` `utilizing` `namespace` `std;` ` `  `lengthy` `lengthy` `subarrayProduct(``int` `n, ``int` `a[])` `{` `    ` `    ` `    ``vector<``lengthy` `lengthy``> suff(n, 0);` ` `  `    ``lengthy` `lengthy` `x = a[n - 2], y = a[n - 1];` `    ``suff[n - 2] = x * y;` `    ``int` `j = n - 1;` ` `  `    ` `    ``for` `(``int` `i = n - 3; i >= 0; i--) {` `        ``x += a[i];` `        ``suff[i] = x * y;` `        ``whereas` `(suff[i] < (x - a[j - 1]) * (y + a[j - 1])) {` `            ``j--;` `            ``x -= a[j];` `            ``y += a[j];` `            ``suff[i] = x * y;` `        ``}` `    ``}` `    ``lengthy` `lengthy` `l = 0, ans = 0;` ` `  `    ` `    ``for` `(``int` `i = 0; i + 2 < n; i++) {` `        ``l += a[i];` `        ``ans = max(ans, l * suff[i + 1]);` `    ``}` `    ``return` `ans;` `}` ` `  `int` `essential()` `{` `    ``int` `A[] = { 1, 2, 2, 3 };` `    ``int` `N = ``sizeof``(A) / ``sizeof``(A[0]);` ` `  `    ` `    ``cout << subarrayProduct(N, A) << endl;` `    ``return` `0;` `}`

Time Complexity: O(N)
Auxiliary House: O(N)