File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change @@ -79,3 +79,38 @@ public int maxSubArray(int[] nums) {
79
79
}
80
80
}
81
81
}
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
+ }
You can’t perform that action at this time.
0 commit comments