Skip to content

Commit eb74efc

Browse files
committedApr 22, 2022
feat: add maximum subarray dynamic programing
1 parent f06874b commit eb74efc

File tree

3 files changed

+36
-4
lines changed

3 files changed

+36
-4
lines changed
 
848 Bytes
Binary file not shown.

‎leetcode/greedy_algorithm/maximum_subarray.cpp

+34-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* @Author: Chacha
33
* @Date: 2022-04-18 14:53:00
44
* @Last Modified by: Chacha
5-
* @Last Modified time: 2022-04-18 15:19:30
5+
* @Last Modified time: 2022-04-22 13:48:28
66
*/
77

88
/**
@@ -42,10 +42,12 @@ class Solution
4242
/* data */
4343
public:
4444
int maxSubArray(vector<int> &nums);
45+
46+
int maxSubArray1(vector<int> &nums);
4547
};
4648

4749
/**
48-
* 贪心解法
50+
* 方法一:贪心解法
4951
*
5052
* 贪心贪的是哪里呢?如果 -2 1 在一起,计算起点的时候,一定是从 1 开始计算,因为负数只会拉低总和,这就是贪心贪的地方。
5153
*
@@ -60,6 +62,9 @@ class Solution
6062
* if (count > result) result = count;
6163
* 这样相当于是用result记录最大子序和区间和(变相的算是调整了终止位置)。
6264
*
65+
* 时间复杂度:O(n)
66+
* 空间复杂度:O(1)
67+
*
6368
*/
6469
int Solution::maxSubArray(vector<int> &nums)
6570
{
@@ -86,6 +91,30 @@ int Solution::maxSubArray(vector<int> &nums)
8691
return result;
8792
};
8893

94+
int Solution::maxSubArray1(vector<int> &nums)
95+
{
96+
if (nums.size() == 0)
97+
{
98+
return 0;
99+
}
100+
101+
vector<int> dp(nums.size(), 0); // dp[i] 表示包括 i 之前的最大连续子序列和
102+
dp[0] = nums[0];
103+
int result = dp[0];
104+
105+
for (int i = 1; i < nums.size(); i++)
106+
{
107+
dp[i] = max(dp[i - 1] + nums[i], nums[i]); // 状态转移方程
108+
109+
if (dp[i] > result)
110+
{
111+
result = dp[i]; // result 保存 dp[i] 的最大值
112+
}
113+
}
114+
115+
return result;
116+
};
117+
89118
int main(int argc, char const *argv[])
90119
{
91120
Solution s;
@@ -95,5 +124,8 @@ int main(int argc, char const *argv[])
95124
std::cout << "[-2, 1, -3, 4, -1, 2, 1, -5, 4]最大子数组和: " << s.maxSubArray(nums) << std::endl;
96125
std::cout << "[5, 4, -1, 7, 8]最大子数组和: " << s.maxSubArray(nums1) << std::endl;
97126

127+
std::cout << "\n[-2, 1, -3, 4, -1, 2, 1, -5, 4]最大子数组和: " << s.maxSubArray1(nums) << std::endl;
128+
std::cout << "[5, 4, -1, 7, 8]最大子数组和: " << s.maxSubArray1(nums1) << std::endl;
129+
98130
return 0;
99131
}

‎leetcode/greedy_algorithm/wiggle_subsequence.cpp

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
* @Author: Chacha
33
* @Date: 2022-04-16 23:18:10
44
* @Last Modified by: Chacha
5-
* @Last Modified time: 2022-04-17 23:05:41
5+
* @Last Modified time: 2022-04-22 11:07:50
66
*/
77

88
/**
@@ -96,7 +96,7 @@ int Solution::wiggleMaxLength(vector<int> &nums)
9696
};
9797

9898
/**
99-
* 动态规划
99+
* 方法二:动态规划
100100
*
101101
* 很容易发现,对于我们当前考虑的这个数,要么是作为山峰(即nums[i] > nums[i-1]),要么是作为山谷(即nums[i] < nums[i - 1])。
102102
* 1. 设dp状态dp[i][0],表示考虑前i个数,第i个数作为山峰的摆动子序列的最长长度

0 commit comments

Comments
 (0)
Failed to load comments.