Lc53_最大子序和

package com.example.leetcode;

/**
 * @description: 53. 最大子序和 --贪心解法
 * 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
 * <p>
 * <p>
 * <p>
 * 示例 1:
 * <p>
 * 输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
 * 输出:6
 * 解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
 * 示例 2:
 * <p>
 * 输入:nums = [1]
 * 输出:1
 * 示例 3:
 * <p>
 * 输入:nums = [0]
 * 输出:0
 * 示例 4:
 * <p>
 * 输入:nums = [-1]
 * 输出:-1
 * 示例 5:
 * <p>
 * 输入:nums = [-100000]
 * 输出:-100000
 * <p>
 * <p>
 * 提示:
 * <p>
 * 1 <= nums.length <= 3 * 104
 * -105 <= nums[i] <= 105
 * <p>
 * <p>
 * 进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。
 * @author: licm
 * @create: 2021-05-13 09:43
 **/
public class Lc53_最大子序和 {

    public static int maxSubArray(int[] nums) {
        int res = 0;
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            count += nums[i];
            count = count < 0 ? 0 : count;
            res = res > count ? res : count;
        }
        return res;
    }

    public static void main(String[] args) {

        int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
        System.out.println(maxSubArray(nums));
    }
}





posted @ 2021-05-13 09:53  小傻孩丶儿  阅读(67)  评论(0编辑  收藏  举报