zoukankan      html  css  js  c++  java
  • 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.

    class Solution {
        public int maxSubArray(int[] nums) {
             if(nums==null||nums.length==0) return 0;
                
                int maxSum=nums[0];//最大和。初始值要为第一项
                int theSum=nums[0];//当前项为止的最大和。初始值要为第一项,不要为0
            //如果当前项的最大和小于等于0,那么theSum应该要从该项后面开始重新计算和,因为负数对和没有正帮助。
    for(int i=1;i<nums.length;i++){ if(theSum>0) theSum=theSum+nums[i]; else theSum=nums[i];//初始值不为零,则这里初始化时也就不是0, if(maxSum<theSum) maxSum=theSum; } return maxSum; } }

    初始为0,若只有一个元素,且为负数,此时就会输出0.不对

  • 相关阅读:
    jsonp 的 post
    js replace常用用法
    zindex
    x秒前
    手写jsonp
    webview 冒泡慢?
    人民币大写转阿拉伯数字
    checked
    Deadlock Troubleshooting Trace 1222
    [转]基于LUCENE实现自己的推荐引擎
  • 原文地址:https://www.cnblogs.com/xiaolovewei/p/8065925.html
Copyright © 2011-2022 走看看