Skip to content

Commit a05ec15

Browse files
author
applewjg
committed
Maximum Subarray
Change-Id: I9b3057c4080dcaae52da93db46900274b3b0f0b0
1 parent 4fe9f44 commit a05ec15

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

MaximumSubarray.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/*
2+
Author: King, [email protected]
3+
Date: Dec 25, 2014
4+
Problem: Maximum Subarray
5+
Difficulty: Medium
6+
Source: https://oj.leetcode.com/problems/maximum-subarray/
7+
8+
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
9+
For example, given the array [-2,1,-3,4,-1,2,1,-5,4], the contiguous subarray [4,-1,2,1] has the largest sum = 6.
10+
11+
Solution: dp.
12+
*/
13+
public class Solution {
14+
public int maxSubArray_1(int[] A) {
15+
if (A.length == 0) return 0;
16+
int minVal = Math.min(A[0],0), res = A[0], sum = A[0];
17+
for (int i = 1; i < A.length; ++i) {
18+
sum += A[i];
19+
res = Math.max(res, sum - minVal);
20+
minVal = Math.min(minVal, sum);
21+
}
22+
return res;
23+
}
24+
public int maxSubArray_2(int[] A) {
25+
if (A.length == 0) return 0;
26+
int dp = A[0], res = A[0];
27+
for (int i = 1; i < A.length; ++i) {
28+
dp = Math.max(A[i], dp + A[i]);
29+
res = Math.max(res, dp);
30+
}
31+
return res;
32+
}
33+
}

0 commit comments

Comments
 (0)