파비의 매일매일 공부기록

Today's Challenge 본문

Problem Solving/LeetCode

Today's Challenge

fabichoi 2022. 6. 11. 23:45

https://leetcode.com/problems/minimum-operations-to-reduce-x-to-zero/

 

Minimum Operations to Reduce X to Zero - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

오늘은 시간이 없어서 일단 소스만 제출하고 패스.
조금 있다가 읽어봐야지

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
         # find the longest subarray that sum to 'goal'
        s = sum(nums)
        n = len(nums)
        goal = s - x
        max_length = -1
        left = 0
        current_sum = 0

        for right, num in enumerate(nums):
            current_sum += num
            # if larger, move `left` to right
            while current_sum > goal and left <= right:
                current_sum -= nums[left]
                left += 1
            # check if equal
            if current_sum == goal:
                max_length = max(max_length, right-left+1)

        return n - max_length if max_length != -1 else -1
반응형

'Problem Solving > LeetCode' 카테고리의 다른 글

Today's Challenge  (0) 2022.06.13
Today's Challenge  (0) 2022.06.12
Today's Challenge  (0) 2022.06.10
Today's Challenge  (0) 2022.06.09
Today's Challenge  (0) 2022.06.08
Comments