LeetCode 1658: Minimum Operations to Reduce X to Zero

Problem Description

Explanation

To solve this problem, we can use a two-pointer sliding window approach. We start by moving the right pointer to the end of the array while calculating the total sum of elements. Then, we move the left pointer to the right until the total sum is greater than x. At each step, we update the minimum operations required based on the window size. If the total sum equals x, we update the result with the minimum of current operations and window size. Finally, we return the result if it is not Integer.MAX_VALUE, else we return -1.

  • Initialize variables: result = Integer.MAX_VALUE, total = 0, left = 0.
  • Iterate the right pointer from 0 to n-1:
    • Calculate total sum += nums[right].
    • While total > x:
      • Subtract nums[left] from total and move left pointer to the right.
    • If total == x, update result with minimum of result and window size.
  • Return result if not Integer.MAX_VALUE, else return -1.

Time complexity: O(n) where n is the length of the input array nums. Space complexity: O(1)

Solutions

class Solution {
    public int minOperations(int[] nums, int x) {
        int n = nums.length;
        int result = Integer.MAX_VALUE;
        int total = 0;
        int left = 0;

        for (int right = 0; right < n; right++) {
            total += nums[right];
            while (total > x) {
                total -= nums[left];
                left++;
            }
            if (total == x) {
                result = Math.min(result, n - (right - left + 1));
            }
        }

        return result != Integer.MAX_VALUE ? result : -1;
    }
}

Loading editor...