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 7a377bd

Browse files
add python of 53
1 parent 96855b9 commit 7a377bd

File tree

8 files changed

+60
-14
lines changed
  • codes
    • java/leetcodes/src/main/java/com/hit/basmath/interview/top_interview_questions/easy_collection/dynamic_programming
    • python/leetcodes/src/main/python/com/hit/basmath

8 files changed

+60
-14
lines changed

‎README.md‎

Lines changed: 9 additions & 9 deletions
Large diffs are not rendered by default.

‎codes/java/leetcodes/src/main/java/com/hit/basmath/interview/top_interview_questions/easy_collection/dynamic_programming/_53.java‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,11 +18,17 @@
1818
*/
1919
public class _53 {
2020
public int maxSubArray(int[] nums) {
21-
int maxSoFar = nums[0], maxEndingHere = nums[0];
22-
for (int i = 1; i < nums.length; ++i) {
23-
maxEndingHere = Math.max(maxEndingHere + nums[i], nums[i]);
24-
maxSoFar = Math.max(maxSoFar, maxEndingHere);
21+
int n = nums.length;
22+
// dp[i] means the maximum subarray ending with nums[i]
23+
int[] dp = new int[n];
24+
dp[0] = nums[0];
25+
int max = dp[0];
26+
27+
for (int i = 1; i < n; i++) {
28+
dp[i] = nums[i] + (dp[i - 1] > 0 ? dp[i - 1] : 0);
29+
max = Math.max(max, dp[i]);
2530
}
26-
return maxSoFar;
31+
32+
return max;
2733
}
2834
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
"""
2+
53. Maximum Subarray
3+
4+
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
5+
6+
Example:
7+
8+
Input: [-2,1,-3,4,-1,2,1,-5,4],
9+
Output: 6
10+
Explanation: [4,-1,2,1] has the largest sum = 6.
11+
Follow up:
12+
13+
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
14+
"""
15+
16+
17+
def maxSubArray(self, nums):
18+
"""
19+
:type nums: List[int]
20+
:rtype: int
21+
"""
22+
numsLen = len(nums)
23+
dp = [nums[0]]
24+
maxSubSum = nums[0]
25+
26+
i = 1
27+
while i < numsLen:
28+
if dp[i - 1] > 0:
29+
temp = dp[i - 1]
30+
else:
31+
temp = 0
32+
33+
dp.append(nums[i] + temp)
34+
35+
if maxSubSum < dp[i]:
36+
maxSubSum = dp[i]
37+
38+
i += 1
39+
40+
return maxSubSum

0 commit comments

Comments
(0)

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