diff --git a/README.md b/README.md index 5f30ea9190..843461f141 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,7 @@ _If you like this project, please leave me a star._ ★ |-----|----------------|---------------|--------|-------------|------------- |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| |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| +|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| |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| |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| |1652|[Defuse the Bomb](https://leetcode.com/problems/defuse-the-bomb/)|[Solution](../master/src/main/java/com/fishercoder/solutions/_1652.java) ||Easy|Array| diff --git a/javascript/_1658.js b/javascript/_1658.js new file mode 100644 index 0000000000..d308fb73a0 --- /dev/null +++ b/javascript/_1658.js @@ -0,0 +1,25 @@ +// Author: Phuong Lam + +/** + * @param {number[]} nums + * @param {number} x + * @return {number} + */ +var minOperations = function (nums, x) { + const total = nums.reduce((a, b) => a + b) + if (total === x) return nums.length + + var sum = 0 + var head = 0 + var max = -1 + for (var tail = 0; tail < nums.length; tail++) { + sum += nums[tail] + while (sum > total - x) { + sum -= nums[head] + head++ + } + if (sum === total - x) max = Math.max(max, tail - head + 1) + } + + return max === -1 ? -1 : nums.length - max +}