LeetCode每日一题:Day7

发布于 2023-01-07  34 次阅读


1658. 将 x 减到 0 的最小操作数

难度

  • Easy
  • Medium
  • Hard

思路

跟圣诞节周赛的第二题基本一样。枚举即可。

代码

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        n = len(nums)
        if sum(nums) == x: return n
        if min(nums) > x: return -1
        j = n
        ans = inf

        while x > 0 and j > 0:
            j -= 1
            x -= nums[j]
        if x == 0: ans = n - j

        for i in range(n):
            x -= nums[i]
            while (i == j or x < 0) and j < n:
                x += nums[j]
                j += 1
            if x == 0:
                ans = min(ans, i + 1 + (n - j))
        return ans if ans != inf else -1