Java implementation of Kadane’s Algorithm(solution to Maximum Subarray Problem).

a = { -2, 1, -3, 4, -1, 2, 1, -5, 4 }
OUT:
Sum: 6 start: 3 end: 6
// © 2019 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net
public class Main {

    public static void main(String[] args) {
        int[] a = { -2, 1, -3, 4, -1, 2, 1, -5, 4 };

        int maxEndingHere = a[0];
        int startIndex = 0;
        int startIndexOld = 0;
        int endIndex = 0;
        int maxSoFar = 0;

        for(int i = 0; i < a.length; ++i){
            maxEndingHere = max(a[i], maxEndingHere + a[i]);
            maxSoFar = max(maxSoFar, maxEndingHere);

            if(maxEndingHere < 0){
                startIndex = i + 1;
            }else if(maxEndingHere == maxSoFar){
                startIndexOld = startIndex;
                endIndex = i;
            }
        }

        System.out.println("Sum: " + maxSoFar + " start: " + startIndexOld + " end: " + endIndex);
    }

    private static int max(int a, int b){
        return a > b ? a : b;
    }
}

 



Java Kadane’s Algorithm
Tagged on:     

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close