Reverse Subarray To Maximize Array Value in C++

C++Server Side ProgrammingProgramming

Suppose we have one integer array called nums. The value of this array is defined as the sum of |nums[i]-nums[i+1]| for all i in range 0 to n - 1. Where n is the size of the array. We can select any subarray of the given array and reverse it. We can perform this operation only once. Then we have to find the maximum possible value of the final array.

So, if the input is like [1,5,4,2,3], then the output will be 10.

To solve this, we will follow these steps −

  • ret := 0, extra := 0

  • n := size of nums

  • minVal := inf, maxVal := -inf

  • for initialize i := 0, when i < n - 1, update (increase i by 1), do −

    • a := nums[i], b := nums[i + 1]

    • ret := ret + |b - a|

    • extra := maximum of extra and |(nums[0] - b) - |a - b||

    • extra := maximum of extra and |(nums[n - 1] - a) - |a - b||

    • maxVal := maximum of maxVal and minimum of a and b

    • minVal := minimum of minVal and maximum of a and b

  • return ret + maximum of extra and (maxVal - minVal) * 2

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
   public:
   int maxValueAfterReverse(vector<int>& nums) {
      int ret = 0;
      int extra = 0;
      int n = nums.size();
      int minVal = INT_MAX;
      int maxVal = INT_MIN;
      for(int i = 0; i < n - 1; i++){
         int a = nums[i];
         int b = nums[i + 1];
         ret += abs(b - a);
         extra = max(extra, abs(nums[0] - b) - abs(a - b));
         extra = max(extra, abs(nums[n - 1] - a) - abs(a - b));
         maxVal = max(maxVal, min(a, b));
         minVal = min(minVal, max(a, b));
      }
      return ret + max(extra, (maxVal - minVal) * 2);
   }
};
main(){
   Solution ob;
   vector<int> v = {1,5,4,2,3};
   cout << (ob.maxValueAfterReverse(v));
}

Input

{1,5,4,2,3}

Output

10
raja
Published on 08-Jun-2020 11:27:43
Advertisements