leetcode53.最大子序和

很经典的一道题,在数据结构课程中也涉及到过,使用贪心是最优解,达到O(n)的时间复杂度

下面给出解释:

  • 首先对数组进行遍历,当前最大连续子序列和为 sum,结果为 ans;
  • 如果 sum > 0,则说明 sum 对结果有增益效果,则 sum 保留并加上当前遍历数字;
  • 如果 sum <= 0,则说明 sum 对结果无增益效果,需要舍弃,则 sum 直接更新为当前遍历数字;
  • 每次比较 sum 和 ans 的大小,将最大值置为 ans ,遍历结束返回结果;
  • 时间复杂度:O(n)O(n)
class Solution {
    public int maxSubArray(int[] nums) {
        int res = nums[0];
        int sum = 0;
        for (int num : nums) {
            if (sum > 0){
                sum += num;
            } else {
                sum = num;
            }
            res = Math.max(res, sum);
        }
        return res;
    }

    public static void main(String[] args) {
        int[] arr = {-2,1,-3,4,-1,2,1,-5,4};
        int res = new Solution().maxSubArray(arr);
        System.out.println(res);
    }
}

你可能感兴趣的:(LeetCode)