LeetCode OJ平台上Maximum Subarray题目O(n)复杂度解决方案

5 篇文章 0 订阅

原始题目如下,意为寻找数组和最大的子串,返回这个最大和即可。

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.

最普通的方法就是两层循环来寻找,复杂度为O(n^2).

在木易先森的指导下,有一个极其简单的O(n)复杂度的方法:

-    先找出数组max值,如果max小于0 ,啥也别说了,直接返回max.

-    设置辅助变量currentmax=0;数组从头至尾扫描一遍

     -    如果currentmax + A[i] <= 0,意味着这个子串对于我们寻找最大和是没有任何帮助的,此时,直接再置currentmax = 0

     -    如果currentmax + A[i] > 0,意味着这个子串的和是有意义的,将这个和跟max比较,时刻保持max的值是当前最理想的最大值

-    最后返回max即可

源代码如下:

public class Solution {
    public static int maxSubArray(int[] A) {
        if(A.length == 0)
            return 0;
        int max = A[0];
        for(int i = 0; i < A.length; i ++)
            if(A[i] > max)
                max = A[i];
        if(max <= 0)
            return max;
        int currentmax = 0;
        for(int i = 0;i < A.length; i ++){
        	currentmax += A[i];
        	if(currentmax <= 0){
        		currentmax = 0;
        		continue;
        		}
        	else{
        		if(currentmax > max)
        			max = currentmax;
        	}
        	}
        return max;
        }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值