最大子序列问题---Kadane’s Algorithm(Dynamic programming(二))

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_15642411/article/details/86773505

Kadane’s Algorithm:

初始化:
    max_so_far = 0
    max_ending_here = 0

遍历arr中每一个元素
  (a) max_ending_here = max_ending_here + a[i]
  (b) if(max_ending_here < 0)
            max_ending_here = 0
  (c) if(max_so_far < max_ending_here)
            max_so_far = max_ending_here
return max_so_far

最大子序列之和

int maxSubArraySum(int a[], int size)
{
   int max_so_far = a[0];
   int curr_max = a[0];

   for (int i = 1; i < size; i++)
   {
        curr_max = max(a[i], curr_max+a[i]);//Kadane's algorithm
        //最大连续子序列之和,最大连续子序列之积,乘法换成+就是连续子序列之和 时间复杂度是o(n)
        max_so_far = max(max_so_far, curr_max);
   }
   return max_so_far;
}

最大子序列之积

int maxSubArraySum(int a[], int size)
{
   int max_so_far = a[0];
   int curr_max = a[0];

   for (int i = 1; i < size; i++)
   {
        curr_max = max(a[i], curr_max*a[i]);//Kadane's algorithm
        //最大连续子序列之和,最大连续子序列之积,乘法换成+就是连续子序列之和 时间复杂度是o(n)
        max_so_far = max(max_so_far, curr_max);
   }
   return max_so_far;
}

时间复杂度 o(n)

猜你喜欢

转载自blog.csdn.net/qq_15642411/article/details/86773505