Given an array A of dimension N. In a single operation just one subarray will be chosen and changed with the sum of the subarray. The duty is to search out the utmost dimension of the array after making it non-decreasing.
Enter: N = 5, A = 5, 1, 6, 6, 6
Rationalization: most dimension non-decreasing array, on this case, is 6, 6, 6, 6 which is obtained by changing subarray(0, 1) = A + A = 6
Enter: N = 9, A = 5, 1, 6, 7, 7, 1, 6, 4, 5
Rationalization: most dimension non-decreasing array, on this case, is 5, 7, 7, 7, 7, 9 which is obtained by changing subarray(1, 2) = A + A = 7. Subarray(5, 6) = A + A = 7. Subarray(7, 8) = A + A = 9
Strategy: This drawback will be solved utilizing grasping method based mostly on the beneath commentary:
Iterate linearly and contemplate the primary aspect to be made up of subarray from 0 to i. Now to search out the remaining components, discover the minimal dimension subarray whose sum is no less than similar because the earlier aspect.
Observe the beneath steps to implement the thought:
- Let the primary aspect of the ultimate non-decreasing subarray be begin.
- Iterate from i = 0 to N-1,
- Calculate begin because the sum of the prefix of the array until i.
- For every worth of begin, iterate from j = i+1, and initialize temp=1
- temp retailer the worth of the scale of optimum non-decreasing array dimension for the present worth of begin.
- Take into account subarray ranging from j till the sum of the subarray is bigger than equal to begin.
- If a subarray is discovered then, improve the temp by 1 and replace the begin to the brand new subarray sum.
- Proceed this iteration until j turns into N.
- The utmost worth of temp amongst all iterations is the reply.
Beneath is the Implementation of the above method:
Time Complexity: O(N * N)
Auxiliary area: O(1)