码迷,mamicode.com
首页 > 其他好文 > 详细

Get the largest sum of contiguous subarray in an int array

时间:2014-06-04 15:30:52      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:c   style   class   blog   code   java   

  When I finished reading this problem,I thought I could solve it by scan every single subarray in the array,and the time complexity is cubic.Every subarray could be the eventual one whose sum is the largest,so I did make a conclusion that the best time complexity is quadratic,and the only optimization is to reduce the times of addition,because I can keep track of the sum from array[i] to array[j] with a table(say table[arraylength][arraylength]).But even this DP-like skill can not reduce the time complexity to O(n).Then my friend told me there are room to optimize it,and the best time complexity is right O(n).

  My first reaction is HOW.After think it over,I found I just miss something tricky.In the process of iteration,we could hit a position whose subarray sum is negative(say i,then array[0]+...+array[i]<0),then we can and should throw this part away.It is because negative sum would contribute negative factor to the following sum we are to look for.With this cool pattern,the time complexity can be optimized to O(n).The below is my code,please let me know if there is anything wrong.Thanks.

bubuko.com,布布扣
 1 /*
 2 author:zhouyou
 3 date:2014/6/2
 4 */
 5 #include <iostream>
 6 #include <limits>
 7 #include <algorithm>
 8 
 9 using namespace std;
10 
11 int GetMaxContiguousSubarraySum(int array[],const int arraylength)
12 {
13     if(!array || arraylength<=0){
14         return numeric_limits<int>::min();//for error,return minimum of int
15     }
16 
17     int current_max = array[0];
18     int Ret = array[0];
19     for(int i=1;i<arraylength;++i){
20         current_max = max(array[i],current_max+array[i]);
21         Ret = max(current_max,Ret);
22     }
23     return Ret;
24 }
25 
26 int main()
27 {
28     int array[6] = {1,2,4,-4,3,6};

29     cout << GetMaxContiguousSubarraySum(array,6) << endl;
30     return 0;
31 }
bubuko.com,布布扣

 

 

Get the largest sum of contiguous subarray in an int array,布布扣,bubuko.com

Get the largest sum of contiguous subarray in an int array

标签:c   style   class   blog   code   java   

原文地址:http://www.cnblogs.com/zhouyoulie/p/3764907.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!