Skip to content

Commit

Permalink
feat: solve maximum subarray
Browse files Browse the repository at this point in the history
  • Loading branch information
GangBean committed Dec 25, 2024
1 parent 4c6e48b commit 0c544eb
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions maximum-subarray/GangBean.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
class Solution {
public int maxSubArray(int[] nums) {
/**
1. understanding
- integer array nums
- find largest subarray sum
2. starategy
- calculate cumulative sum
- mem[i+1] = num[i+1] + mem[i] if (num[i+1] + mem[i] >= 0) else num[i+1]
3. complexity
- time: O(N)
- space: O(1)
*/
int prev = 0;
int curr = 0;
int max = Integer.MIN_VALUE;
for (int i = 0 ; i < nums.length; i++) {
curr = nums[i];
if (prev >= 0) {
curr += prev;
}
max = Math.max(max, curr);
prev = curr;
}
return max;
}
}

0 comments on commit 0c544eb

Please sign in to comment.