/**
* Problem: LeetCode 1658 - Minimum Operations to Reduce X to Zero
* Difficulty: Medium
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int minOperations(int[] nums, int x) {
int total = 0;
for (int num : nums) total += num;
int target = total - x;
if (target < 0) return -1;
if (target == 0) return nums.length;
int maxLen = -1;
int windowSum = 0;
int left = 0;
for (int right = 0; right < nums.length; right++) {
windowSum += nums[right];
while (windowSum > target && left <= right) {
windowSum -= nums[left];
left++;
}
if (windowSum == target) {
maxLen = Math.max(maxLen, right - left + 1);
}
}
return maxLen == -1 ? -1 : nums.length - maxLen;
}
}
"""
Problem: LeetCode 1658 - Minimum Operations to Reduce X to Zero
Difficulty: Medium
Language: Python
Author: CodeByTushu
"""
from typing import List
class Solution:
def minOperations(self, nums: List[int], x: int) -> int:
total = sum(nums)
target = total - x
if target < 0:
return -1
if target == 0:
return len(nums)
max_len = -1
window_sum = 0
left = 0
for right in range(len(nums)):
window_sum += nums[right]
while window_sum > target and left <= right:
window_sum -= nums[left]
left += 1
if window_sum == target:
max_len = max(max_len, right - left + 1)
return -1 if max_len == -1 else len(nums) - max_len
/**
* Problem: LeetCode 1658 - Minimum Operations to Reduce X to Zero
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
#include <vector>
#include <numeric>
#include <algorithm>
/**
* Problem: LeetCode 1658 - Minimum Operations to Reduce X to Zero
* Difficulty: Medium
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int minOperations(std::vector<int>& nums, int x) {
long long total = 0;
for (int num : nums) total += num;
long long target = total - x;
if (target < 0) return -1;
if (target == 0) return static_cast<int>(nums.size());
int maxLen = -1;
long long windowSum = 0;
int left = 0;
int n = static_cast<int>(nums.size());
for (int right = 0; right < n; right++) {
windowSum += nums[right];
while (windowSum > target && left <= right) {
windowSum -= nums[left];
left++;
}
if (windowSum == target) {
maxLen = std::max(maxLen, right - left + 1);
}
}
return maxLen == -1 ? -1 : n - maxLen;
}
};
/**
* Problem: LeetCode 1658 - Minimum Operations to Reduce X to Zero
* Difficulty: Medium
* Language: JavaScript
* Author: CodeByTushu
*/
var minOperations = function(nums, x) {
let total = 0;
for (let i = 0; i < nums.length; i++) {
total += nums[i];
}
const target = total - x;
if (target < 0) return -1;
if (target === 0) return nums.length;
let maxLen = -1;
let windowSum = 0;
let left = 0;
for (let right = 0; right < nums.length; right++) {
windowSum += nums[right];
while (windowSum > target && left <= right) {
windowSum -= nums[left];
left++;
}
if (windowSum === target) {
maxLen = Math.max(maxLen, right - left + 1);
}
}
return maxLen === -1 ? -1 : nums.length - maxLen;
};