53. Maximum Subarray
Given an integer array nums
, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
Example:
Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6.
Follow up:
If you have figured out the O(n) solution, try coding another solution using the divide and conquer approach, which is more subtle.
AC code:
class Solution { public: int maxSubArray(vector<int>& nums) { int len = nums.size(); if (len == 1) return nums[0]; vector<int> dp(len, 0); dp[0] = nums[0]; int maxx = dp[0]; for (int i = 1; i < len; ++i) { dp[i] = nums[i] + (dp[i-1] > 0? dp[i-1] : 0); maxx = max(maxx, dp[i]); } return maxx; } };
Runtime: 4 ms, faster than 100.00% of C++ online submissions for Maximum Subarray
2021-04-17
给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。
示例 1:
输入:nums = [-2,1,-3,4,-1,2,1,-5,4]
输出:6
解释:连续子数组 [4,-1,2,1] 的和最大,为 6 。
示例 2:
输入:nums = [1]
输出:1
示例 3:
输入:nums = [0]
输出:0
示例 4:
输入:nums = [-1]
输出:-1
示例 5:
输入:nums = [-100000]
输出:-100000
提示:
1 <= nums.length <= 3 * 104
-105 <= nums[i] <= 105
进阶:如果你已经实现复杂度为 O(n) 的解法,尝试使用更为精妙的 分治法 求解。
思路:
这题也算是一道DP题,因为当前的最大子序和和它前面的那个元素是有关系的。定义一个数组f[n]用来表示nums[0....n]的最大子序和,如果f[i-1] > 0,则f[i] = f[i-1] + v[i];如果f[i-1] < 0,则f[i] = v[i];最后的结果就是数组f[n]中的最大值。
代码:
#include <algorithm> #include <iostream> #include <vector> using namespace std; int main() { int n; cin >> n; vector<int> v(n); for (int i = 0; i < n; ++i) { cin >> v[i]; } vector<int> f(n, 0); f[0] = v[0]; for (int i = 1; i < n; ++i) { if (f[i - 1] > 0) f[i] = f[i - 1] + v[i]; else f[i] = v[i]; } cout << *max_element(f.begin(), f.end()) << endl; return 0; }