Skip to content

Commit 5578cd0

Browse files
committedApr 25, 2025
Add solution #1658
1 parent 641e19b commit 5578cd0

File tree

2 files changed

+44
-1
lines changed

2 files changed

+44
-1
lines changed
 

‎README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# 1,455 LeetCode solutions in JavaScript
1+
# 1,456 LeetCode solutions in JavaScript
22

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

@@ -1278,6 +1278,7 @@
12781278
1655|[Distribute Repeating Integers](./solutions/1655-distribute-repeating-integers.js)|Hard|
12791279
1656|[Design an Ordered Stream](./solutions/1656-design-an-ordered-stream.js)|Easy|
12801280
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|
12811282
1668|[Maximum Repeating Substring](./solutions/1668-maximum-repeating-substring.js)|Easy|
12821283
1669|[Merge In Between Linked Lists](./solutions/1669-merge-in-between-linked-lists.js)|Medium|
12831284
1672|[Richest Customer Wealth](./solutions/1672-richest-customer-wealth.js)|Easy|
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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+
};

0 commit comments

Comments
 (0)
Please sign in to comment.