How to find the maximum sum of a subarray in Java

1 Answer

0 votes
import java.util.Arrays;

public class Program {
    public static int maxSubArray(int[] arr) {
        int maxSum = Integer.MIN_VALUE;
        int currentSum = 0;
        int size = arr.length;
        
        for (int i = 0; i < size; i++) {
            currentSum = Math.max(arr[i], currentSum + arr[i]);
            maxSum = Math.max(currentSum, maxSum);
        }
        
        return maxSum;
    }

    public static void main(String[] args) {
        int[] arr = {1, -2, 2, -3, 4, -1, -1, 2, 3, -5, 4}; // 4 + -1 + -1 + 2 + 3 = 7
        
        System.out.println(maxSubArray(arr));
    }
}




/*
run:

7

*/

 



answered Feb 25, 2024 by avibootz
...