Minimum Operations to Reduce X to Zero

Medium

Description

Given an integer array nums and an integer x, return the minimum number of operations to reduce x to exactly 0 by removing leftmost or rightmost element.

Examples

Input:nums = [1,1,4,2,3], x = 5
Output:2
Explanation:

Remove rightmost 3 and 2.

Input:nums = [2,1,3,4,1], x = 6
Output:3
Explanation:

Remove leftmost 2 and 1, then remove rightmost 1. Total removed: 2+1+1=4, remaining sum would be 7, but the requirement is exactly 6, so removing 2,1 from left and 3 from right: 2+1+3=6.

Input:nums = [1,2,3,4,5], x = 15
Output:5
Explanation:

The sum of all elements is exactly 15, so the task requires remove all elements from the array. It is possible to remove all 5 elements from either end or any combination from both ends.

Constraints

  • 1 ≤ nums.length ≤ 10⁵

Ready to solve this problem?

Practice solo or challenge other developers in a real-time coding battle!