最大子数组和
maximum subarray (最大子数组和)
This is my first blog i wrote by English. if you have any question about grammar or others , i'm glad to talk with you
Original : Maximum Subarray
Question :
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Sample :
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest sum = 6.
Solution :
we can solve the question using dp.
presume that the coordinate of the nums array range from \(0\) to \(n - 1\). \(dp[i]\) denoted that the maximum from \(0\) to \(i\).therefore , the formula is as follows:
c++ code
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int MAX = -10000 - 1;
int n = nums.size();
vector<int> dp(n + 1,0);
for(int i = 1;i <= n;i++){
dp[i] = max(dp[i - 1] + nums[i - 1] , nums[i - 1]);
MAX = MAX>dp[i]?MAX:dp[i];
}
return MAX;
}
};
we noticed that this formula are only relative with \(i\) and \(i - 1\).so we can further reduce the memory used. namely that we use two variables for recording \(dp[i]\) and \(dp[i - 1]\) respectively. therefore c++ code modified are as follows:
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int MAX = -10000 - 1;
int n = nums.size();
int pre = 0,cur;
for(int i = 0;i < n;i++){
cur = max(pre + nums[i] , nums[i]);
MAX = MAX>cur?MAX:cur;
pre = cur;
}
return MAX;
}
};

浙公网安备 33010602011771号