returns the maximum subarray (contiguous elements) in an array - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

returns the maximum subarray (contiguous elements) in an array

Demo Code


//package com.java2s;
import java.util.Arrays;

public class Main {
    /**//from ww  w  .  j a v a2 s.c  o m
     * A famous problem that returns the maximum subarray (contiguous elements)
     * in an array 
     *     - solved using Kadane's algorithm
     * @param list
     * @return
     */
    public static Integer[] maxSubarray(Integer[] list) {
        int maxSoFar = 0;
        int maxToHere = 0;
        int l = 0;
        int r = 0;
        int temp = 0;
        for (int a = 0; a < list.length; a++) {
            if (maxToHere < 0) {
                maxToHere = list[a];
                temp = a;
            } else {
                maxToHere += list[a];
            }

            if (maxToHere >= maxSoFar) {
                maxSoFar = maxToHere;
                l = temp;
                r = a;
            }
        }
        System.out.println((l) + " " + (r) + " max: " + maxSoFar);
        return Arrays.copyOfRange(list, l, r);
    }
}

Related Tutorials