LeetCode - 53. Maximum Subarray

Description

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.

Solution

解题思路参考了

  1. Kadane算法

  2. @LiamHuang said in DP solution & some thoughts:

    When we are talking about DP, the first problem comes out to our mind should be: what's the statement of the sub-problem, whose format should satisfy that if we've solved a sub-problem, it would be helpful for solving the next-step sub-problem, and, thus, eventually helpful for solving the original problem.

    Here is the sub-problem we state: denote int_local_max[i] as the max-sub-array-sum that ends with nums[i]. The relationship between the two steps is simple: int_local_max[i + 1] = max (int_local_max[i] + nums[i + 1], nums[i + 1]) or int_local_max[i + 1] = (int_local_max[i] > 0) ? int_local_max[i] + nums[i + 1] : nums[i + 1].

    Now, all we have to do is to scan through the array, and find which int_local_max[i] is the maximum of all the int_local_maxs.

python

 1 class Solution(object):
 2     def maxSubArray(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: int
 6         """
 7         # [-2,1,-3,4,-1,2,1,-5,4]
 8         max_num = max(nums)
 9         if max_num < 0:
10             return max_num
11 
12         max_sum = 0
13         cur_sum = 0
14         nums_len = len(nums)
15         for i in range(nums_len):
16             cur_sum = cur_sum + nums[i]
17             if cur_sum < 0:
18                 cur_sum = 0
19                 continue
20 
21             if cur_sum > max_sum:
22                 max_sum = cur_sum
23 
24         return max_sum

 

cpp

 1 class Solution {
 2 public:
 3     int maxSubArray(vector<int>& nums) {
 4         if (nums.size() == 0)
 5             return 0;
 6 
 7         if (nums.size() == 1)
 8             return nums.at(0);
 9 
10         int max_sum = nums.at(0);
11         int cur_sum = nums.at(0);
12         size_t length = nums.size();
13         for (size_t i=1; i<length; ++i)
14         {
15             cur_sum = max(cur_sum + nums.at(i), nums.at(i));
16             max_sum = max(cur_sum, max_sum);
17         }
18 
19         return max_sum;
20     }
21 }; 

Reference

posted @ 2017-03-27 15:23  朝研行歌  阅读(149)  评论(0编辑  收藏  举报