Skip to content

Commit d4376b6

Browse files
committed
Add solution #1330
1 parent 7b125c6 commit d4376b6

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

README.md

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,234 LeetCode solutions in JavaScript
1+
# 1,235 LeetCode solutions in JavaScript
22

33
[https://leetcodejavascript.com](https://leetcodejavascript.com)
44

@@ -1008,6 +1008,7 @@
10081008
1326|[Minimum Number of Taps to Open to Water a Garden](./solutions/1326-minimum-number-of-taps-to-open-to-water-a-garden.js)|Hard|
10091009
1328|[Break a Palindrome](./solutions/1328-break-a-palindrome.js)|Medium|
10101010
1329|[Sort the Matrix Diagonally](./solutions/1329-sort-the-matrix-diagonally.js)|Medium|
1011+
1330|[Reverse Subarray To Maximize Array Value](./solutions/1330-reverse-subarray-to-maximize-array-value.js)|Hard|
10111012
1331|[Rank Transform of an Array](./solutions/1331-rank-transform-of-an-array.js)|Easy|
10121013
1332|[Remove Palindromic Subsequences](./solutions/1332-remove-palindromic-subsequences.js)|Easy|
10131014
1333|[Filter Restaurants by Vegan-Friendly, Price and Distance](./solutions/1333-filter-restaurants-by-vegan-friendly-price-and-distance.js)|Medium|
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 1330. Reverse Subarray To Maximize Array Value
3+
* https://leetcode.com/problems/reverse-subarray-to-maximize-array-value/
4+
* Difficulty: Hard
5+
*
6+
* You are given an integer array nums. The value of this array is defined as the sum
7+
* of |nums[i] - nums[i + 1]| for all 0 <= i < nums.length - 1.
8+
*
9+
* You are allowed to select any subarray of the given array and reverse it. You can
10+
* perform this operation only once.
11+
*
12+
* Find maximum possible value of the final array.
13+
*/
14+
15+
/**
16+
* @param {number[]} nums
17+
* @return {number}
18+
*/
19+
var maxValueAfterReverse = function(nums) {
20+
let baseSum = 0;
21+
let maxGain = 0;
22+
let minPair = Infinity;
23+
let maxPair = -Infinity;
24+
const n = nums.length;
25+
26+
for (let i = 0; i < n - 1; i++) {
27+
baseSum += Math.abs(nums[i] - nums[i + 1]);
28+
minPair = Math.min(minPair, Math.max(nums[i], nums[i + 1]));
29+
maxPair = Math.max(maxPair, Math.min(nums[i], nums[i + 1]));
30+
}
31+
32+
maxGain = Math.max(0, 2 * (maxPair - minPair));
33+
34+
for (let i = 0; i < n - 1; i++) {
35+
const left = i > 0 ? Math.abs(nums[0] - nums[i + 1]) - Math.abs(nums[i] - nums[i + 1]) : 0;
36+
const right = i < n - 2 ? Math.abs(nums[n - 1] - nums[i]) - Math.abs(nums[i] - nums[i + 1]) : 0;
37+
maxGain = Math.max(maxGain, left, right);
38+
}
39+
40+
return baseSum + maxGain;
41+
};

0 commit comments

Comments
 (0)