Title Description: Given the nums an array of integers, and find a maximum of the successive sub-array (sub-array comprising a minimum element) having its maximum and returns.
Example:
输入: [-2,1,-3,4,-1,2,1,-5,4],
输出: 6
解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。
This problem using brute-force method, the left end to the right end of the enumeration, required complexity O (n2) time, and then add calculations, for a total time complexity O (n3), which is clearly unacceptable. At this point we think of dynamic programming to solve the problem.
Dynamic Programming: Let array dp [i] represented by [i] num is the largest continuous sequence and ending elements. By providing such a DP [] array, the last requirement is the DP [] largest element. Because dp [I] in claim must num [i] is the end of the element, the dp [I] values are only two cases: one contains one element, i.e. num [i] itself; i.e., 2 comprises a plurality of elements dp [i] = dp [i- 1] + [i] num, we only need to do in both cases the maximum value is assigned to dp [i] to, i.e. dp [i] = max (num [i ], dp [i-1] + num [i]). This algorithm is a boundary dp [0] = num [0 ], can then be calculated sequentially behind dp [i] a value.
Code:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int length=nums.size();
int dp[length];
dp[0]=nums[0];//边界
for(int i=1;i<length;i++){
dp[i]=max(nums[i],dp[i-1]+nums[i]);
}
int k=0;
for(int i=1;i<length;i++){
if(dp[i]>dp[k])
k=i;
}
return dp[k];
}
};
operation hours: