页首是什么<\h1>

编程习题——Maximum Subarray

Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
the contiguous subarray [4,−1,2,1] has the largest sum = 6.

 

public class Test08 {

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

        int[] sums = new int[nums.length];
        int max = nums[0];
        sums[0] = nums[0];
        for (int i = 1; i < nums.length; i++) {
            sums[i] = Math.max(nums[i], nums[i] + sums[i - 1]);
            max = Math.max(max, sums[i]);
        }
        System.out.println(max);
    }

}

 

 

posted @ 2014-04-16 12:22  YES_eng  阅读(141)  评论(0编辑  收藏  举报