File tree 2 files changed +43
-1
lines changed
2 files changed +43
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,234 LeetCode solutions in JavaScript
1
+ # 1,235 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
1008
1008
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|
1009
1009
1328|[ Break a Palindrome] ( ./solutions/1328-break-a-palindrome.js ) |Medium|
1010
1010
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|
1011
1012
1331|[ Rank Transform of an Array] ( ./solutions/1331-rank-transform-of-an-array.js ) |Easy|
1012
1013
1332|[ Remove Palindromic Subsequences] ( ./solutions/1332-remove-palindromic-subsequences.js ) |Easy|
1013
1014
1333|[ Filter Restaurants by Vegan-Friendly, Price and Distance] ( ./solutions/1333-filter-restaurants-by-vegan-friendly-price-and-distance.js ) |Medium|
Original file line number Diff line number Diff line change
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
+ } ;
You can’t perform that action at this time.
0 commit comments