Leetcode 53. Maximum Subarray [easy][java]

本文深入探讨了寻找具有最大和的连续子数组算法。通过迭代更新当前和最大值,实现高效求解。适用于整数数组,算法核心在于判断是否将当前元素加入到已有的子数组中,还是作为新的子数组的开始。

Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Example

Consideration

  1. We use a sum to represent the current sum. If adding current num can let sum larger than the previous one, we add this num to sum. Otherwise, we let sum equals to the current num.
  2. In each iteration, we compare the sum with the maximal result at the time. And update the maximal result if necessary.

== Solution ==

class Solution {
    public int maxSubArray(int[] nums) {
        if(nums == null || nums.length == 0)
            return 0;
        int sum = nums[0];
        int max = sum;
        for(int i = 1; i < nums.length; i++) {
            sum += nums[i];
            if(sum < nums[i])
                sum = nums[i];
            if(max<sum)
                max = sum;
        }
        
        return max;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值