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 mn = INT_MAX;
    int mx = INT_MIN;

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

    for (int i = 0; i + 1 < nums.size(); ++i) {
      const int a = nums[i];
      const int b = nums[i + 1];
      const int headDiff = -abs(a - b) + abs(nums.front() - b);
      const int tailDiff = -abs(a - b) + abs(nums.back() - a);
      diff = 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 mn = Integer.MAX_VALUE;
    int mx = Integer.MIN_VALUE;

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

    for (int i = 0; i + 1 < nums.length; ++i) {
      final int a = nums[i];
      final int b = nums[i + 1];
      final int headDiff = -Math.abs(a - b) + Math.abs(nums[0] - b);
      final 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:
    mn = math.inf
    mx = -math.inf

    for a, b in zip(nums, nums[1:]):
      mn = min(mn, max(a, b))
      mx = max(mx, min(a, b))
    diff = max(0, (mx - mn) * 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