You might be given an array A[] of measurement N, the duty is to divide the array into precisely three subarrays such that each ingredient 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
Rationalization: The optimum partitions are {1, 2}, {2}, {3}Enter: N = 3, A[] = { 3, 5, 7}
Output: 105
Rationalization: There is just one attainable partition {3}, {5}, {7}.
Strategy: This drawback could be solved utilizing the idea of sliding window and prefix-suffix array.
First, calculate the utmost product of two subarrays contemplating the scale of the array from 0 to N ranging from proper. Now as soon as we’ve the utmost product of two subarrays then the third subarray will likely be on the left facet.
For instance, if we’ve 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 are able to calculate the utmost product of those two subarrays to get most product of three subarrays.
Observe the steps talked about beneath to implement the thought.
- Create a suffix array of measurement 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 increase the subarray with sum x by 1 and hold sliding the subarray with sum y in the 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].
Beneath is the implementation of the above method:
C++
|
|
Time Complexity: O(N)
Auxiliary Area: O(N)