Skip to content

1330. Reverse Subarray To Maximize Array Value 👍

  • Time:
  • Space:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution {
 public:
  int maxValueAfterReverse(vector<int>& nums) {
    int total = 0;
    int min = INT_MAX;
    int max = INT_MIN;

    for (int i = 0; i + 1 < nums.size(); ++i) {
      int a = nums[i];
      int b = nums[i + 1];
      total += abs(a - b);
      min = std::min(min, std::max(a, b));
      max = std::max(max, std::min(a, b));
    }
    int diff = std::max(0, (max - min) * 2);

    for (int i = 0; i + 1 < nums.size(); ++i) {
      int a = nums[i];
      int b = nums[i + 1];
      int headDiff = -abs(a - b) + abs(nums.front() - b);
      int tailDiff = -abs(a - b) + abs(nums.back() - a);
      diff = std::max({diff, headDiff, tailDiff});
    }

    return total + diff;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
class Solution {
  public int maxValueAfterReverse(int[] nums) {
    int total = 0;
    int min = Integer.MAX_VALUE;
    int max = Integer.MIN_VALUE;

    for (int i = 0; i + 1 < nums.length; ++i) {
      int a = nums[i];
      int b = nums[i + 1];
      total += Math.abs(a - b);
      min = Math.min(min, Math.max(a, b));
      max = Math.max(max, Math.min(a, b));
    }
    int diff = Math.max(0, (max - min) * 2);

    for (int i = 0; i + 1 < nums.length; ++i) {
      int a = nums[i];
      int b = nums[i + 1];
      int headDiff = -Math.abs(a - b) + Math.abs(nums[0] - b);
      int tailDiff = -Math.abs(a - b) + Math.abs(nums[nums.length - 1] - a);
      diff = Math.max(diff, Math.max(headDiff, tailDiff));
    }

    return total + diff;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
class Solution:
  def maxValueAfterReverse(self, nums: List[int]) -> int:
    mini = math.inf
    maxi = -math.inf

    for a, b in zip(nums, nums[1:]):
      mini = min(mini, max(a, b))
      maxi = max(maxi, min(a, b))
    diff = max(0, (maxi - mini) * 2)

    for a, b in zip(nums, nums[1:]):
      headDiff = -abs(a - b) + abs(nums[0] - b)
      tailDiff = -abs(a - b) + abs(nums[-1] - a)
      diff = max(diff, headDiff, tailDiff)

    return sum(abs(a - b) for a, b in zip(nums, nums[1:])) + diff
Back to top