forked from kumailn/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaximum_Subarray.py
More file actions
19 lines (15 loc) · 773 Bytes
/
Copy pathMaximum_Subarray.py
File metadata and controls
19 lines (15 loc) · 773 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# Question: Find the sum of a continuous subarray in an array with the largest sum
# Solution: Kadane's algorithm (explained below)
# Difficulty: Easy
# Time Complexity: O(n)
# Space Complexity: O(n)
from typing import List
def maxSubArray(nums: List[int]) -> int:
# Initialize a store for the local and global maximum sumarrays
localMax = globalMax = float('-inf')
for i, v in enumerate(nums):
# LocalMax becomes the larger of the current number or the current number + localMax itself
localMax = max(v, v + localMax)
# If localMax happens to become larger than globalMax, set globalMax to localMax
if localMax > globalMax: globalMax = localMax
return globalMax