Table of contents
How to learn dynamic programming?
How to learn dynamic programming?
There is no shortcut to learning an algorithm, let alone learning dynamic programming,
Brush dynamic programming algorithm questions with me, and learn dynamic programming together!
1. Topic analysis
Topic Link: 53. Maximum Subarray Sum - LeetCode
The topic is easy to understand. As the name suggests, it is to find the largest sub-array sum.
2. Algorithm principle
1. Status representation
The position dp[ i ] represents the maximum sum of all subarrays ending with the element at position i.
2. State transition equation
The state transition equation has two cases,
1. When the length of the subarray is 1, the maximum sum is the value at position i
2. If the length of the sub-array is greater than 1, the maximum sum is the maximum sum of the previous position + the value of the current position
So we can get the state transition equation
dp [ i ] = max( nums[ i ],dp[ i ] + nums[ i ] )
3. Initialization
Initialization is to prevent out-of-bounds, and does not affect subsequent values,
Just initialize it to 0.
4. Filling order
Just go from left to right.
5. Return value
Returns the maximum value in the entire dp table.
3. Code writing
class Solution {
public:
int maxSubArray(vector<int>& nums) {
int n = nums.size();
vector<int> dp(n + 1);
int ans = INT_MIN;
for(int i = 1; i <= n ; i++) {
dp[i] = max(nums[i - 1], dp[i - 1] + nums[i - 1]);
ans = max(ans, dp[i]);
}
return ans;
}
};
Write at the end:
The above is the content of this article, thank you for reading.
If you feel that you have gained something, you can give the blogger a like .
If there are omissions or mistakes in the content of the article, please private message the blogger or point it out in the comment area~