Site icon

Find maximum sum subarray in java using Kadane’s algorithm

Examples: maximum sum subarray in java using Kadane’s algorithm

Example 1

Example 2

Example 3

Kadane’s algorithm to find maximum sum subarray in java

Time complexity of algorithm is O (n).

Program – maximum sum subarray in java using Kadane’s algorithm

package org.learn.arrays;

import java.util.Arrays;

public class KadaneMaxSumSubArray {

	private static void maxSubArray(int[] input) {
		
		int localMax = 0;
		int maxSum = Integer.MIN_VALUE;

		for (int index = 0; index < input.length; index++) {

			localMax = localMax + input[index];			
			localMax = Math.max(0, localMax);
			maxSum = Math.max(maxSum, localMax);
		}
		
		System.out.printf("%d",maxSum);
	}

	public static void main(String[] args) {

		int array[] = { -2, 2, 1, -3, 1};	
		String sArray = Arrays.toString(array);
		
		System.out.printf("1. Max sum sub array in %s is : ",sArray);
		maxSubArray(array);
		
		array = new int[]{ -2, 2, 3, -3, 4};	
		sArray = Arrays.toString(array);
		
		System.out.printf("\n2. Max sum sub array in %s is : ",sArray);
		maxSubArray(array);
		
		array = new int[]{ 1 , 2, -4, 4, -1, -2, 4};	
		sArray = Arrays.toString(array);
		System.out.printf("\n3. Max sum sub array in %s is : ",sArray);
		maxSubArray(array);
	}	
}

Output – maximum sum subarray in java using Kadane’s algorithm

1. Max sum sub array in [-2, 2, 1, -3, 1] is : 3
2. Max sum sub array in [-2, 2, 3, -3, 4] is : 6
3. Max sum sub array in [1, 2, -4, 4, -1, -2, 4] is : 5
Exit mobile version