1413. Minimum Value to Get Positive Step by Step Sum

2021. 11. 11. 20:16Leetcode

Description:

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.

'''
[1] prefix sum)

code::
def minStartValue(self, nums: List[int]) -> int:
    prefix=copy.deepcopy(nums)

    for i in range(1,len(nums)):
        prefix[i]+=prefix[i-1]

    min_value=0
    for num in prefix:
        min_value=min(min_value,num)

    return 1-min_value
    
-T/C: O(n)  # three-pass
-S/C: O(n)
'''

'''
[2] optimization)

idea::
in-place and while making prefix sum, find min_value

code::
(below)

-T/C: O(n)  # one-pass
-S/C: O(1) 
'''
class Solution:
    def minStartValue(self, nums: List[int]) -> int:
        min_value=min(0,nums[0])
        
        for i in range(1,len(nums)):
            nums[i]+=nums[i-1]
            min_value=min(min_value,nums[i])
            
        return 1-min_value

'Leetcode' 카테고리의 다른 글

367. Valid Perfect Square  (0) 2021.11.12
203. Remove Linked List Elements  (0) 2021.11.12
23. Merge k Sorted Lists  (0) 2021.11.10
122. Best Time to Buy and Sell Stock II  (0) 2021.11.10
21. Merge Two Sorted Lists  (0) 2021.11.10