Skip to content

Commit 9fb6d3c

Browse files
committed
revision- finds maximum subarray sum, O(N) Time, O(1) space
1 parent 9caba04 commit 9fb6d3c

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package practice.revisited;
2+
3+
// leetcode 53. Maximum Subarray
4+
public class MaximumSubarrayLC53 {
5+
6+
public static int maxSubArray(int[] nums) {
7+
8+
int maxsum = Integer.MIN_VALUE;
9+
int currsum = 0;
10+
11+
for (int n : nums) {
12+
13+
currsum += n;
14+
maxsum = Math.max(currsum, maxsum);
15+
16+
if (currsum < 0)
17+
currsum = 0;
18+
}
19+
20+
return maxsum;
21+
}
22+
23+
public static void main(String[] args) {
24+
int[] arr = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };
25+
System.out.println(maxSubArray(arr));
26+
27+
System.out.println(maxSubArray(new int[] { 1 }));
28+
System.out.println(maxSubArray(new int[] { 5, 4, -1, 7, 8 }));
29+
}
30+
}

0 commit comments

Comments
Β (0)