java.lang.Object
g1601_1700.s1658_minimum_operations_to_reduce_x_to_zero.Solution

public class Solution extends Object
1658 - Minimum Operations to Reduce X to Zero.<p>Medium</p> <p>You are given an integer array <code>nums</code> and an integer <code>x</code>. In one operation, you can either remove the leftmost or the rightmost element from the array <code>nums</code> and subtract its value from <code>x</code>. Note that this <strong>modifies</strong> the array for future operations.</p> <p>Return <em>the <strong>minimum number</strong> of operations to reduce</em> <code>x</code> <em>to <strong>exactly</strong></em> <code>0</code> <em>if it is possible</em>_, otherwise, return_ <code>-1</code>.</p> <p><strong>Example 1:</strong></p> <p><strong>Input:</strong> nums = [1,1,4,2,3], x = 5</p> <p><strong>Output:</strong> 2</p> <p><strong>Explanation:</strong> The optimal solution is to remove the last two elements to reduce x to zero.</p> <p><strong>Example 2:</strong></p> <p><strong>Input:</strong> nums = [5,6,7,8,9], x = 4</p> <p><strong>Output:</strong> -1</p> <p><strong>Example 3:</strong></p> <p><strong>Input:</strong> nums = [3,2,20,1,1,3], x = 10</p> <p><strong>Output:</strong> 5</p> <p><strong>Explanation:</strong> The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.</p> <p><strong>Constraints:</strong></p> <ul> <li><code>1 <= nums.length <= 10<sup>5</sup></code></li> <li><code>1 <= nums[i] <= 10<sup>4</sup></code></li> <li><code>1 <= x <= 10<sup>9</sup></code></li> </ul>
  • Constructor Details

    • Solution

      public Solution()
  • Method Details

    • minOperations

      public int minOperations(int[] nums, int x)