https://leetcode.com/problems/maximum-subarray/?envType=featured-list&envId=top-interview-questions
Kadane's Algorithm (Greedy and DP)
배열의 최대 부분합을 O(n)의 시간 복잡도로 구하는 알고리즘
KEY POINT: 이전의 부분합을 안다면 그 인덱스까지의 부분합은 재계산할 필요가 없다.
Greedy: we are keeping a running sum of integers and when it becomes less than 0, we reset it to 0
DP: at each stage, we have 2 choices: Either take the current element and continue with the previous sum OR restart a new range. Both choices are being taken care of in the implementation.
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
curSum, maxSum = 0, nums[0]
for n in nums:
if curSum < 0:
curSum = 0
curSum += n
maxSum = max(maxSum, curSum)
return maxSum
Reference
'스터디 로그 > Computer Science' 카테고리의 다른 글
[Python] *args, **kwargs, and return vs. yield (Generator) (1) | 2024.02.08 |
---|---|
[Robotics] Sensor Fusion, Autonomous Systems (2) | 2023.10.30 |
[C] C언어의 무기, 포인터 (1) | 2023.01.29 |
[VirtualBox] Mac에서의 가상머신 사용기 (0) | 2023.01.03 |
[Robotics] 맥에서 가상 환경 시작하기 + ROS2 설치 (0) | 2022.12.31 |