Skip to content

Commit 9f01518

Browse files
authored
1658 solution (#137)
* Add solution for problem 1658 in javascript * Add missing file * Update README.md
1 parent 114489b commit 9f01518

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ _If you like this project, please leave me a star._ ★
1010
|-----|----------------|---------------|--------|-------------|-------------
1111
|1663|[Smallest String With A Given Numeric Value](https://leetcode.com/problems/smallest-string-with-a-given-numeric-value/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_1663.java) ||Medium|Greedy|
1212
|1662|[Check If Two String Arrays are Equivalent](https://leetcode.com/problems/check-if-two-string-arrays-are-equivalent/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_1662.java) ||Easy|String|
13+
|1658|[Minimum Operations to Reduce X to Zero](https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/)|[Javascript](./javascript/_1658.js)||Medium|Greedy|
1314
|1657|[Determine if Two Strings Are Close](https://leetcode.com/problems/determine-if-two-strings-are-close/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_1657.java) ||Medium|Greedy|
1415
|1656|[Design an Ordered Stream](https://leetcode.com/problems/design-an-ordered-stream/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_1656.java) ||Easy|Array, Design|
1516
|1652|[Defuse the Bomb](https://leetcode.com/problems/defuse-the-bomb/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_1652.java) ||Easy|Array|

Diff for: javascript/_1658.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Author: Phuong Lam
2+
3+
/**
4+
* @param {number[]} nums
5+
* @param {number} x
6+
* @return {number}
7+
*/
8+
var minOperations = function (nums, x) {
9+
const total = nums.reduce((a, b) => a + b)
10+
if (total === x) return nums.length
11+
12+
var sum = 0
13+
var head = 0
14+
var max = -1
15+
for (var tail = 0; tail < nums.length; tail++) {
16+
sum += nums[tail]
17+
while (sum > total - x) {
18+
sum -= nums[head]
19+
head++
20+
}
21+
if (sum === total - x) max = Math.max(max, tail - head + 1)
22+
}
23+
24+
return max === -1 ? -1 : nums.length - max
25+
}

0 commit comments

Comments
 (0)