1658. Minimum Operations to Reduce X to Zero Medium

@problem@discussion
#Array#Hash Table#Binary Search#Sliding Window#Prefix Sum



1/**
2 * [1658] Minimum Operations to Reduce X to Zero
3 *
4 * You are given an integer array nums and an integer x. In one operation, you can either remove the leftmost or the rightmost element from the array nums and subtract its value from x. Note that this modifies the array for future operations.
5 * Return the minimum number of operations to reduce x to exactly 0 if it is possible, otherwise, return -1.
6 *  
7 * Example 1:
8 * 
9 * Input: nums = [1,1,4,2,3], x = 5
10 * Output: 2
11 * Explanation: The optimal solution is to remove the last two elements to reduce x to zero.
12 * 
13 * Example 2:
14 * 
15 * Input: nums = [5,6,7,8,9], x = 4
16 * Output: -1
17 * 
18 * Example 3:
19 * 
20 * Input: nums = [3,2,20,1,1,3], x = 10
21 * Output: 5
22 * Explanation: The optimal solution is to remove the last three elements and the first two elements (5 operations in total) to reduce x to zero.
23 * 
24 *  
25 * Constraints:
26 * 
27 * 	1 <= nums.length <= 10^5
28 * 	1 <= nums[i] <= 10^4
29 * 	1 <= x <= 10^9
30 * 
31 */
32pub struct Solution {}
33
34// problem: https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/
35// discuss: https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/discuss/?currentPage=1&orderBy=most_votes&query=
36
37// submission codes start here
38
39impl Solution {
40    pub fn min_operations(nums: Vec<i32>, x: i32) -> i32 {
41        0
42    }
43}
44
45// submission codes end
46
47#[cfg(test)]
48mod tests {
49    use super::*;
50
51    #[test]
52    fn test_1658() {
53    }
54}
55


Back
© 2025 bowen.ge All Rights Reserved.