File tree 2 files changed +44
-1
lines changed
2 files changed +44
-1
lines changed Original file line number Diff line number Diff line change 1
- # 1,455 LeetCode solutions in JavaScript
1
+ # 1,456 LeetCode solutions in JavaScript
2
2
3
3
[ https://leetcodejavascript.com ] ( https://leetcodejavascript.com )
4
4
1278
1278
1655|[ Distribute Repeating Integers] ( ./solutions/1655-distribute-repeating-integers.js ) |Hard|
1279
1279
1656|[ Design an Ordered Stream] ( ./solutions/1656-design-an-ordered-stream.js ) |Easy|
1280
1280
1657|[ Determine if Two Strings Are Close] ( ./solutions/1657-determine-if-two-strings-are-close.js ) |Medium|
1281
+ 1658|[ Minimum Operations to Reduce X to Zero] ( ./solutions/1658-minimum-operations-to-reduce-x-to-zero.js ) |Medium|
1281
1282
1668|[ Maximum Repeating Substring] ( ./solutions/1668-maximum-repeating-substring.js ) |Easy|
1282
1283
1669|[ Merge In Between Linked Lists] ( ./solutions/1669-merge-in-between-linked-lists.js ) |Medium|
1283
1284
1672|[ Richest Customer Wealth] ( ./solutions/1672-richest-customer-wealth.js ) |Easy|
Original file line number Diff line number Diff line change
1
+ /**
2
+ * 1658. Minimum Operations to Reduce X to Zero
3
+ * https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/
4
+ * Difficulty: Medium
5
+ *
6
+ * You are given an integer array nums and an integer x. In one operation, you can either remove
7
+ * the leftmost or the rightmost element from the array nums and subtract its value from x. Note
8
+ * that this modifies the array for future operations.
9
+ *
10
+ * Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise,
11
+ * return -1.
12
+ */
13
+
14
+ /**
15
+ * @param {number[] } nums
16
+ * @param {number } x
17
+ * @return {number }
18
+ */
19
+ var minOperations = function ( nums , x ) {
20
+ const targetSum = nums . reduce ( ( sum , num ) => sum + num , 0 ) - x ;
21
+ if ( targetSum < 0 ) return - 1 ;
22
+ if ( targetSum === 0 ) return nums . length ;
23
+
24
+ let currentSum = 0 ;
25
+ let maxLength = - 1 ;
26
+ let left = 0 ;
27
+
28
+ for ( let right = 0 ; right < nums . length ; right ++ ) {
29
+ currentSum += nums [ right ] ;
30
+
31
+ while ( currentSum > targetSum && left <= right ) {
32
+ currentSum -= nums [ left ] ;
33
+ left ++ ;
34
+ }
35
+
36
+ if ( currentSum === targetSum ) {
37
+ maxLength = Math . max ( maxLength , right - left + 1 ) ;
38
+ }
39
+ }
40
+
41
+ return maxLength === - 1 ? - 1 : nums . length - maxLength ;
42
+ } ;
You can’t perform that action at this time.
0 commit comments