Leetcode - Minimum Operations to Reduce X to Zero

Ji Kim·2021년 1월 15일
0

Algorithm

목록 보기
33/34

Minimum Operations to Reduce X to Zero

Description

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 1

Input

nums = [1,1,4,2,3], x = 5

Output

2

Example 2

Input

nums = [5,6,7,8,9], x = 4

Output

-1

Example 3

Input

nums = [3,2,20,1,1,3], x = 10

Output

5

Approach

Using sliding window algorithm, simply set the range of elements within the array with maximum sum which equals the target (sum of entire array minus the input x). And then after storing the maximum length of two indices left and right, subtract the value to the total length of array

Solution (Python)

class Solution(object):
    def minOperations(self, nums, x):
        target = sum(nums) - x
        
        if target == 0:
            return len(nums)
        
        left, right = 0, 0 
        curr, cnt = 0, 0 
        
        while right < len(nums):
            curr = curr + nums[right]
            
            while left < right and curr > target:
                curr = curr - nums[left]
                left = left + 1
            if curr == target:
                cnt = max(cnt, right - left + 1)
            right = right + 1
            
        if cnt == 0:
            return -1 
        else:
            return len(nums) - cnt 

Result

Runtime : 1012ms
Memory Usage : 24.4MB
Runtime Beats 89.62% of Python Submission

profile
if this then that

0개의 댓글