Maximum Subarray Sum in Java: Explanation & Practice
Find the maximum sum of a contiguous subarray
Problem summary
Write a program that finds the maximum sum of any contiguous subarray (Kadane's algorithm).
Starter code
public class Main {
public static void main(String[] args) {
int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4}; // Test case 1
// Find max subarray sum
// Print: Max sum: <result>
}
}Expected output and test cases
- [4,-1,2,1] = 6
Max sum: 6
- All positive sums
Max sum: 5
- All negative, pick largest
Max sum: -1
Hints
- Kadane's: track current sum and max sum
- Reset current sum if it goes negative
- Update max whenever current exceeds it
Related Arrays exercises
Practice all Arrays exercises · Run this idea in the Java compiler