-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaximum-subarray.py
More file actions
30 lines (25 loc) · 845 Bytes
/
maximum-subarray.py
File metadata and controls
30 lines (25 loc) · 845 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# /**
# * @param {number[]} nums
# * @return {number}
# */
# var maxSubArray = function(nums) {
# let maxSum = -Infinity,
# sumSoFar = 0;
# for(let num of nums){
# sumSoFar += num;
# if(sumSoFar > maxSum) {maxSum = sumSoFar};
# if(sumSoFar < 0) {sumSoFar = 0}
# // sumSoFar = Math.max(num, sumSoFar + num); // Take the maximum of current element or adding it to sumSoFar
# // maxSum = Math.max(maxSum, sumSoFar); // Update maxSum if sumSoFar is greater
# }
# return maxSum;
# };
class Solution:
def maxSubArray(self, nums: List[int]) -> int:
maxSum = float('-inf')
sumSoFar = 0
for num in nums:
sumSoFar += num
maxSum = max(maxSum, sumSoFar)
if sumSoFar < 0: sumSoFar = 0
return maxSum