zoukankan      html  css  js  c++  java
  • Maximum Subarray

    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[] A) {
            int max = Integer.MIN_VALUE;
            if(A == null || A.length == 0)  return max;
            int len = A.length;
            for(int i = 0; i < len; i++)
            {
                max = Math.max(A[i],max);
            }
            int curSum = 0;
            for(int i = 0; i < len; i++)
            {
                int cur = A[i];
                if( cur >= 0)
                {
                    curSum += cur;
                    max = Math.max(curSum,max);
                }
                else
                {
                    if(curSum + cur < 0)    curSum = 0;
                    else    curSum += cur;
                }
            }
            return max;
        }
    }
    View Code

    别人代码:

    public class Solution {
        public int maxSubArray(int[] A) {
            if (A == null || A.length == 0){
                return 0;
            }
            
            int max = Integer.MIN_VALUE, sum = 0;
            for (int i = 0; i < A.length; i++) {
                sum += A[i];
                max = Math.max(max, sum);
                sum = Math.max(sum, 0);
            }
    
            return max;
        }
    }
    View Code

    学习之处:

      别人的代码简介,但是不好理解

    need to learn

  • 相关阅读:
    composer国内镜像配置
    composer.json和composer.lock作用
    工厂模式(描述语言PHP)
    PHP后期静态绑定
    js事件冒泡和事件捕获
    去帮助别人,并接受别人的帮助
    平静,问题本身也是问题
    总是被欲望折磨的我
    习惯产生力量
    秦岭野生动物园
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4315839.html
Copyright © 2011-2022 走看看