![]() |
VOOZH | about |
Given an array A[] of length N. Then your task is to output the maximum sum that can be achieved by using the given operation at any number of times (possibly zero):
Examples:
Input: N = 3, A[] = {8, 1, 7}
Output: 22
Explanation: Let us take the subarray A[1, 3] = {8, 1, 7}. Middle element(s) are: {1}. Now minimum of A[1] and A[3] is = min(A[1], A[3]) = min(8, 7) = 7. Then, we replaced all the middle elements equal to min according to the operation. So, updated A[] = {8, 7, 7}. The sum of updated A[] = 22. Which is the maximum possible using a given operation. Therefore, output is 22.Input: N = 2, A[] = {5, 2}
Output: 7
Explanation: No subarray of length at least 3 can be chosen, Thus can't apply any operation. So the maximum possible sum is 7.
Approach: Implement the idea below to solve the problem
The problem is based on the observations and can be solved using the Prefix and Suffix arrays. It must be noticed that for any index i, we can not make the element A[i] to be anything more than the minimum of the greatest element to its left and the greatest element to its right.
Steps were taken to solve the problem:
Code to implement the approach:
7
Time Complexity: O(N)
Auxiliary Space: O(2*N), As Prefix and Suffix arrays of length N are used.