IT公司100题-3-求数组的最大子序列的和

问题描述:java

计算一个给定数组的最大子序列之和数组

求全部子数组的和的最大值。要求时间复杂度为O(n)。this

例如输入的数组为1, -2, 3, 10, -4, 7, 2, -5,和最大的子数组为3, 10, -4, 7, 2spa

所以输出为该子数组的和18。code

分析:
it

有三种方法:io

1,扫描3遍,能够计算全部的子序列之和,可是复杂度为N^3。class

2,扫描2遍,计算以任意元素开始的和,若是大于当前的最大值则将最大值付给它,复杂度为N^2。date

3,扫描一遍,计算任意元素开始的值,若是小于零则清零,不然继续日后加。file


代码实现:

package oschina.IT100;
/**
 * @project: DataStructureAndAlgorithmAnalysis
 * @filename: MaxSubSum
 * @version: 0.10
 * @author: Jimmy Han
 * @date: 21:35 2015/7/7
 * @comment: calculate the sum from any point, reset sum when current sum is negative
 * @result: 10
 */

class IT3 {
   public static void main(String[] args){
      int[] arr = {-1, 3, 2, -3, -1, 4, 5};
      System.out.println(maxSubSum(arr));
   }

   public static int maxSubSum( int[] a){
      int maxSum = 0, thisSum = 0;

      for(int j = 0; j < a.length; j++){
         thisSum += a[j];

         if(thisSum > maxSum)
            maxSum = thisSum;
         else if(thisSum < 0)
            thisSum = 0;
      }

      return maxSum;
   }
}
相关文章
相关标签/搜索