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

  • 相关阅读:
    5大用例设计笔试大题,附详细解析!
    面试被问到:fiddler 在工作中有哪些应用?怎么破?
    Jmeter设置中文
    Git 操作
    测压数据处理脚本
    python通过126邮箱发送邮件
    Python读取Mysql数据并写入Excel
    Git基本操作命令
    python接口自动化框架探讨
    寒假每日一题(B
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4315839.html
Copyright © 2011-2022 走看看