Maximum subarray problem--Kadane’s Algorithm

Maximum subarray problem--Kadane’s Algorithm](http://www.cnblogs.com/xubenben/p/3403597.html)

https://en.wikipedia.org/wiki/Maximum_subarray_problem

Kadane's algorithm[edit]

Kadane's algorithm begins with a simple inductive question: if we know the maximum subarray sum ending at position {\displaystyle i}

i
i
, what is the maximum subarray sum ending at position {\displaystyle i+1}
i+1
i+1
? The answer turns out to be relatively straightforward: either the maximum subarray sum ending at position {\displaystyle i+1}
i+1
i+1
includes the maximum subarray sum ending at position {\displaystyle i}
i
i
as a prefix, or it doesn't. Thus, we can compute the maximum subarray sum ending at position {\displaystyle i}
i
i
for all positions {\displaystyle i}
i
i
by iterating once over the array. As we go, we simply keep track of the maximum sum we've ever seen. Thus, the problem can be solved with the following code, expressed here in Python:

def max_subarray(A):
    max_ending_here = max_so_far = A[0]
    for x in A[1:]:
        max_ending_here = max(x, max_ending_here + x)
        max_so_far = max(max_so_far, max_ending_here)
    return max_so_far

The algorithm can also be easily modified to keep track of the starting and ending indices of the maximum subarray (when max_so_far changes) as well as the case where we want to allow zero-length subarrays (with implicit sum 0) if all elements are negative.

Because of the way this algorithm uses optimal substructures (the maximum subarray ending at each position is calculated in a simple way from a related but smaller and overlapping subproblem: the maximum subarray ending at the previous position) this algorithm can be viewed as a simple/trivial example of dynamic programming.

The runtime complexity of Kadane's algorithm is {\displaystyle O(n)}
O(n)
O(n)

.

Here, I describe variants of Kadane’s algorithm to solve the maximum subarray and the minimum subarray problems. The maximum subarray problem is to find the contiguous subarray having the largest sum. Likewise, the minimum subarray problem is to find the contiguous subarray having the smallest sum. Variants of Kadane’s algorithm can solve these problems in O(N) time.

Kadane’s algorithm uses the dynamic programming approach to find the maximum (minimum) subarray ending at each position from the maximum (minimum) subarray ending at the previous position.

#include <cstdio>
   2:  #include <climits>
   3:  using namespace std;
   4:   
   5:  int maxSum(int *A, int lo, int hi)  {
   6:      int left = lo, right = lo, sum = INT_MIN, currentMaxSum = 0, maxLeft = lo, maxRight = lo;
   7:      for(int i = lo; i < hi; i++)    {
   8:          currentMaxSum += A[i];
   9:          if(currentMaxSum > sum) {
  10:              sum = currentMaxSum;
  11:              right = i;
  12:              maxLeft = left;
  13:              maxRight = right;
  14:          }
  15:          if(currentMaxSum < 0)   {
  16:              left = i+1;
  17:              right = left;
  18:              currentMaxSum = 0;
  19:          }
  20:      }
  21:      printf("Maximum sum contiguous subarray :");
  22:      for(int i = maxLeft; i <= maxRight; i++)
  23:          printf(" %d", A[i]);
  24:      printf("\n");
  25:      return sum;
  26:  }
  27:   
  28:  int minSum(int *A, int lo, int hi)  {
  29:      int left = lo, right = lo, sum = INT_MAX, currentMinSum = 0, minLeft = lo, minRight = lo;
  30:      for(int i = lo; i < hi; i++)    {
  31:          currentMinSum += A[i];
  32:          if(currentMinSum < sum) {
  33:              sum = currentMinSum;
  34:              right = i;
  35:              minLeft = left;
  36:              minRight = right;
  37:          }
  38:          if(currentMinSum > 0)   {
  39:              left = i+1;
  40:              right = left;
  41:              currentMinSum = 0;
  42:          }
  43:      }
  44:      printf("Minimum sum contiguous subarray :");
  45:      for(int i = minLeft; i <= minRight; i++)
  46:          printf(" %d", A[i]);
  47:      printf("\n");
  48:      return sum;
  49:  }
  50:   
  51:  int main()  {
  52:      int A[] = {3, 4, -3, -2, 6};
  53:      int N = sizeof(A) / sizeof(int);
  54:   
  55:      printf("Maximum sum : %d\n", maxSum(A, 0, N));
  56:      printf("Minimum sum : %d\n", minSum(A, 0, N));
  57:   
  58:      return 0;
  59:  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,099评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,473评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,229评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,570评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,427评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,335评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,737评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,392评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,693评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,730评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,512评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,349评论 3 314
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,750评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,017评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,290评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,706评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,904评论 2 335

推荐阅读更多精彩内容

  • 古之立大事者,不唯有超世之才,亦必有坚韧不拔之志。 此句出自苏轼的巜晁错论》,句意为自古以来的能建功立业做大事的人...
    飞桃阅读 801评论 0 0
  • 爱上张小北,让她明白了一个道理,生活远不是两面的,除了黑与白,还存在着很多色彩。 有时候,沉默就是最好的应付。 在...
    凉月牙儿阅读 225评论 0 3
  • 今天是大宝夏令营第二天,带队老师不停地在微信群里发照片,今天的活动有速降和攀岩,这些运动是儿子从没听说过...
    三二班王俊睿妈妈阅读 130评论 0 0
  • 无须昂贵的整型美容,也能淡化眼周肌肤的时光痕迹。全新「水•贝娜眼部抗皱精华液」,质地轻薄,能被眼周肌肤迅速吸收,日...
    水云斋主阅读 363评论 0 0
  • PMBOK指南包含了适用于许多行业、可在大多数时候用来管理大多数项目的标准。 本标准专用于单个项目管理,且仅包含被...
    六月_6阅读 359评论 0 1