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:  }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

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