41.Maximum Subarray-最大子数组(容易题)

来源:互联网 发布:centos openstack 编辑:程序博客网 时间:2024/05/17 02:03

最大子数组

  1. 题目

    给定一个整数数组,找到一个具有最大和的子数组,返回其最大和。

    注意事项

    子数组最少包含一个数

  2. 样例

    给出数组[−2,2,−3,4,−1,2,1,−5,3],符合要求的子数组为[4,−1,2,1],其最大和为6

  3. 挑战

    要求时间复杂度为O(n)

  4. 题解

    贪心法,如果当前curMax或sum小于0则丢弃,否则更新sum。如数组全部由小于0的数组成,则直接返回最大值。

public class Solution {    /**     * @param nums: A list of integers     * @return: A integer indicate the sum of max subarray     */    public int maxSubArray(int[] nums) {        int sum = nums[0];        int curMax = nums[0];        int max = nums[0];        for (int i=1;i<nums.length;i++)        {            curMax = curMax < 0 ? nums[i] : (curMax + nums[i]);            sum = curMax > sum ? curMax : sum;            max = max < nums[i] ? nums[i] : max;        }        return sum < 0 ? max : sum;    }}

Last Update 2016.8.26

0 0
原创粉丝点击