Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit b01373a

Browse files
Maximum Subarray
1 parent c916768 commit b01373a

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
'''Leetcode -https://leetcode.com/problems/maximum-subarray/'''
2+
'''
3+
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
4+
5+
A subarray is a contiguous part of an array.
6+
7+
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
8+
Output: 6
9+
'''
10+
11+
# Solution1
12+
import math
13+
14+
def maxSubArray(nums):
15+
max_s = -math.inf
16+
for i in range(len(nums)):
17+
currentS = 0
18+
for j in range(i, len(nums)):
19+
currentS += nums[j]
20+
max_s = max(max_s, currentS)
21+
return max_s
22+
23+
# T:O(N^2)
24+
# S:O(1)
25+
26+
# Solution2
27+
def maxSubArray(nums):
28+
max_sum = cur_sum = float('-inf')
29+
30+
for i in nums:
31+
cur_sum = max(cur_sum + i, i)
32+
max_sum = max(max_sum, cur_sum)
33+
34+
return max_sum
35+
# T:O(N)
36+
# S:O(1)

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,4 @@ Check the notes for the explaination - [Notes](https://stingy-shallot-4ea.notion
2424

2525
- [x] [Dynamic Programming](Dynamic-Programming)
2626
- [x] [Climbing Stairs](Dynamic-Programming/70-Climbing-Stairs.py)
27+
- [x] [Maximum Subarray](Dynamic-Programming/53-maximum-subarray.py)

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /