AI工具人
提示词工程师

Leetcode 53. Maximum Subarray

题目链接:53.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 Solution {
    public int maxSubArray(int[] nums) {
        int sum = 0;
        int maxsum = nums[0];
        for (int i = 0; i < nums.length; i++) {
            sum += nums[i];
            if (sum > maxsum) {
                maxsum = sum;
            }
            if (sum < 0) {
                sum = 0;
                continue;
            }
        }
        return maxsum;
    }
}
赞(0) 打赏
未经允许不得转载:XINDOO » Leetcode 53. Maximum Subarray

评论 抢沙发

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续给力更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫打赏

微信扫一扫打赏

登录

找回密码

注册