Skip to content

Commit d898555

Browse files
authored
Update 053. Maximum Subarray.java
1 parent 5839ac2 commit d898555

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

053. Maximum Subarray.java

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,3 +79,38 @@ public int maxSubArray(int[] nums) {
7979
}
8080
}
8181
}
82+
83+
84+
// Dynamic Programming approach
85+
public class Solution {
86+
public int maxSubArray(int[] nums) {
87+
if (nums.length == 0) return Integer.MIN_VALUE;
88+
else {
89+
int maxSoFar = nums[0], maxEndingHere = nums[0];
90+
91+
for (int i=1; i < nums.length; i++){
92+
maxEndingHere = Math.max(maxEndingHere + nums[i], nums[i]);
93+
maxSoFar = Math.max(maxSoFar, maxEndingHere);
94+
}
95+
96+
return maxSoFar;
97+
}
98+
}
99+
}
100+
101+
// another formulation
102+
public class Solution {
103+
public int maxSubArray(int[] A) {
104+
//dp[i] means the maximum subarray ending with A[i];
105+
int[] dp = new int[n];
106+
dp[0] = A[0];
107+
int max = dp[0];
108+
109+
for(int i = 1; i < A.length; i++){
110+
dp[i] = (dp[i - 1] > 0 ? dp[i - 1] : 0) + A[i];
111+
max = Math.max(max, dp[i]);
112+
}
113+
114+
return max;
115+
}
116+
}

0 commit comments

Comments
 (0)