学习目标:
买卖股票的最佳时机 II
学习内容:
动态规划
贪心算法
贪心:
①建立数学模型来描述问题 。
②把求解的问题分成若干个子问题 。
③对每个子问题求解,得到子问题的局部最优解 。
④把子问题的局部最优解合成原来解问题的一个解 。
贪心算法也存在如下问题:
1、不能保证解是最佳的。因为贪心算法总是从局部出发,并没从整体考虑
2、贪心算法一般用来解决求最大或最小解
3、贪心算法只能确定某些问题的可行性范围 。
C++
class Solution {
public:
int maxProfit(vector<int>& prices) {
int result = 0;
for(int i=1;i<prices.size();i++){
result += max(0,prices[i]-prices[i-1]);
}
return result;
}
};
python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
profit = 0
for i in range(1, len(prices)):
tmp = prices[i] - prices[i - 1]
if tmp > 0: profit += tmp
return profit
动态规划:
多阶段决策问题中,各个阶段采取的决策,一般来说是与时间有关的,决策依赖于当前状态,又随即引起状态的转移,一个决策序列就是在变化的状态中产生出来的,故有“动态”的含义,称这种解决多阶段决策最优化问题的方法为动态规划方法 。
1、建立状态变化(转移)方程
2、对之前状态进行复用
3、从前到后的进行递归出结果
C++
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
int dp[n][2]; //所有天数的交易状态 0为无股票 1 为持有 可优化为当天和前一天
dp[0][0] = 0, dp[0][1] = -prices[0];
for (int i = 1; i < n; ++i) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[n - 1][0];
}
};
python
class Solution:
def maxProfit(self, prices: List[int]) -> int:
dp0 = 0 # 手里没股票
dp1 = - prices[0] # 手里有股票
for i in range(1, len(prices)):
dp0 = max(dp0, dp1 + prices[i])
dp1 = max(dp1, dp0 - prices[i])
return dp0