LeetCode之“动态规划”:Maximum Subarray

  题目链接

  题目要求:

  Find the contiguous subarray within an array (containing at least one number) which has the largest sum.

  For example, given the array [−2,1,−3,4,−1,2,1,−5,4],
  the contiguous subarray [4,−1,2,1] has the largest sum = 6.

  More practice:

  If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.

  复杂度为O(n)的程序如下:

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         int sz = nums.size();
 5         if(sz == 0)
 6             return 0;
 7             
 8         int maxsofar = INT_MIN;
 9         int sum = 0;
10         for(int i = 0; i < sz; i++)
11         {
12             sum += nums[i];
13             if(sum > maxsofar)
14                 maxsofar = sum;
15             if(sum < 0)
16                 sum = 0;
17         }
18         
19         return maxsofar;
20     }
21 };

   我们也可以利用局部最优和全局最优的思想来解决这个问题(参考自一博文):

  基本思路是这样的,在每一步,我们维护两个变量,一个是全局最优,就是到当前元素为止最优的解是,一个是局部最优,就是必须包含当前元素的最优的解。接下来说说动态规划的递推式(这是动态规划最重要的步骤,递归式出来了,基本上代码框架也就出来了)。假设我们已知第i步的global[i](全局最优)和local[i](局部最优),那么第i+1步的表达式是:local[i+1]=max(A[i], local[i]+A[i]),就是局部最优是一定要包含当前元素,所以不然就是上一步的局部最优local[i]+当前元素A[i](因为local[i]一定包含第i个元素,所以不违反条件),但是如果local[i]是负的,那么加上他就不如不需要的,所以不然就是直接用A[i];global[i+1]=max(local[i+1],global[i]),有了当前一步的局部最优,那么全局最优就是当前的局部最优或者还是原来的全局最优(所有情况都会被涵盖进来,因为最优的解如果不包含当前元素,那么前面会被维护在全局最优里面,如果包含当前元素,那么就是这个局部最优)。

  具体程序如下:

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         int sz = nums.size();
 5         if(sz == 0)
 6             return 0;
 7         
 8         vector<int> local(sz, 0);
 9         vector<int> global(sz, 0);
10         local[0] = nums[0];
11         global[0] = nums[0];
12         for(int i = 1; i < sz; i++)
13         {
14             local[i] = max(nums[i], nums[i] + local[i - 1]);
15             global[i] = max(global[i - 1], local[i]);
16         }
17         
18         return global[sz - 1];
19     }
20 };

  这个程序还可以更节省空间:

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         int sz = nums.size();
 5         if(sz == 0)
 6             return 0;
 7             
 8         int local = nums[0];
 9         int global = nums[0];
10         for(int i = 1; i < sz; i++)
11         {
12             local = max(nums[i], nums[i] + local);
13             global = max(global, local);
14         }
15         
16         return global;
17     }
18 };

 

posted @ 2015-06-11 20:33  峰子_仰望阳光  阅读(636)  评论(0编辑  收藏  举报