(转)Maximum subarray problem--Kadane’s Algorithm

转自:http://kartikkukreja.wordpress.com/2013/06/17/kadanes-algorithm/

本来打算自己写的,后来看到上述链接的博客已经说得很清楚了,就不重复劳动啦.

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.

 

   1:  #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:  }

posted on 2013-11-02 12:53  苯苯吹雪  阅读(1993)  评论(0编辑  收藏  举报

导航