Skip to content

Commit e30131f

Browse files
committed
#53: Maximum Subarray
1 parent f78842a commit e30131f

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

Array/max_subarray.py

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Given an integer array nums, find the subarray with the largest sum,
2+
# and return its sum.
3+
4+
5+
# Example 1:
6+
# Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
7+
# Output: 6
8+
# Explanation: The subarray [4,-1,2,1] has the largest sum 6.
9+
10+
# Example 2:
11+
# Input: nums = [1]
12+
# Output: 1
13+
# Explanation: The subarray [1] has the largest sum 1.
14+
15+
# Example 3:
16+
# Input: nums = [5,4,-1,7,8]
17+
# Output: 23
18+
# Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.
19+
20+
21+
# Constraints:
22+
23+
# 1 <= nums.length <= 105
24+
# -104 <= nums[i] <= 104
25+
26+
27+
from typing import List
28+
29+
class Solution:
30+
def maxSubArray(self, nums: List[int]) -> int:
31+
# Solved using Kadane's Algorithm
32+
current_sum = nums[0]
33+
max_sum = nums[0]
34+
35+
for i in range(1, len(nums)):
36+
current_sum = max(nums[i], current_sum + nums[i])
37+
max_sum = max(current_sum, max_sum)
38+
return max_sum
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# Given an integer array nums, find the subarray with the largest sum,
2+
# and return its sum.
3+
4+
5+
# Example 1:
6+
# Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
7+
# Output: 6
8+
# Explanation: The subarray [4,-1,2,1] has the largest sum 6.
9+
10+
# Example 2:
11+
# Input: nums = [1]
12+
# Output: 1
13+
# Explanation: The subarray [1] has the largest sum 1.
14+
15+
# Example 3:
16+
# Input: nums = [5,4,-1,7,8]
17+
# Output: 23
18+
# Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.
19+
20+
21+
# Constraints:
22+
23+
# 1 <= nums.length <= 105
24+
# -104 <= nums[i] <= 104
25+
26+
27+
from typing import List
28+
29+
class Solution:
30+
def maxSubArray(self, nums: List[int]) -> int:
31+
# Solved using Kadane's Algorithm
32+
current_sum = nums[0]
33+
max_sum = nums[0]
34+
35+
for i in range(1, len(nums)):
36+
current_sum = max(nums[i], current_sum + nums[i])
37+
max_sum = max(current_sum, max_sum)
38+
return max_sum

0 commit comments

Comments
 (0)