Enrollments closing soon for Post Graduate Certificate Program in Applied Data Science & AI By IIT Roorkee | 3 Seats Left

  Apply Now

Data Structures and Algorithms Questions

12 / 13

Minimum Operations to Reduce X to Zero

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.

Return the minimum number of operations to reduce x to exactly 0 if it's possible, otherwise, return -1.

Example:

Input: nums = [1,1,4,2,3], x = 5
Output: 2
Explanation: The optimal solution is to remove the last two elements (first 3 and then 2) from nums, to reduce x to zero.

Input: nums = [5,6,7,8,9], x = 4
Output: -1
Explanation: We can not reduce x to 0 in this case because every element in nums is greater than x

Constraints:

  • 1 <= nums.length <= 105
  • 1 <= nums[i] <= 104
  • 1 <= x <= 109
INSTRUCTIONS

  1. Write your code inside a function named min_operations
  2. Your code should work for all permitted possible values(check Constraints) of nums and x
  3. There are no partial marks for the question.
  4. Your function must return the output, it should not print the output.
  5. To execute a block on the right side coding panel, please press 'shift'+ 'enter'

Complete the below code in the right side coding panel

def min_operations(nums:int, x: int) -> int:
    # your code goes here
See Answer

No hints are availble for this assesment


Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...