1413. Minimum Value to Get Positive Step by Step Sum

Given an array of integers nums, you start with an initial positive value startValue.

In each iteration, you calculate the step by step sum of startValue plus elements in nums (from left to right).

Return the minimum positive value of startValue such that the step by step sum is never less than 1.

startValue使得从左到右加nums里的数的和不小于1,其实就是求个前缀和,然后找前缀和的最小值,如果是正数,返回1,如果是负数,返回负数的绝对值+1

class Solution(object):
    def minStartValue(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        pre_sum = [nums[0]]
        ans = nums[0]
        for i in range(1, len(nums), 1):
            pre_sum.append(pre_sum[i - 1] + nums[i])
            print(pre_sum)
            if ans > pre_sum[i]:
                ans = pre_sum[i]
        if ans > 0:
            return 1
        else:
            return -ans + 1
        

猜你喜欢

转载自www.cnblogs.com/whatyouthink/p/13209977.html