Max Sub Array Sum: Kadane's Algorithm

Code of: Max Sub Array Sum: Kadane's Algorithm.


public class MaxSubArraySumKadanesALgorithm {
    public static void Kadane(int nums[]) {
        int ms = Integer.MIN_VALUE; // maxumum sum
        int cs = 0; // current sum
        // This is basic code of Kadane algorithm, //
        // this code is not useful when all number is -ve.
        // 4 to 5 = answer 7 ms.
        for (int i = 0; i < nums.length; i++) {
            cs = cs + nums[i];
            if (cs < 0) {
                cs = 0;
            }
            ms = Math.max(cs, ms);
        }
        System.out.println("Our max subarray sum is: " + ms);
    }

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


...

No comments:

Post a Comment

Max Sub Array Sum: Kadane's Algorithm

Code of: Max Sub Array Sum: Kadane's Algorithm. public class MaxSubArraySumKadanesALgorithm {     public static void Kadane ( int ...