买卖股票系列
只能买卖一次
这样的话我们使用dp[i]在第i天卖掉股票能获得的最大利益
显然我们要在stock[0 : i]这个区间找到最小值,
我们在遍历的时候可以实时更新这个最小值
dp[0] = 0
min_s = stock[0]
dp[i] = stock[i] - min_s
min_s = min(stock[i], min_s)
可以买卖多次
贪心策略,只要今天比昨天多,就卖掉。 这个里面假如明天比今天少当然这么操作能赚更多 而如果明天比今天多,在明天的时候又有profir += tomorow - today,获得的利润于昨天买,后天卖是一样的
class Solution:
def maxProfit(self, prices) -> int:
ret = 0
if not prices:
return 0
for i in range(1, len(prices)):
if prices[i] > prices[i - 1]:
ret += prices[i] - prices[i - 1]
return ret
只能买卖两次(真dp)
class Solution:
def maxProfit(self, prices) -> int:
if len(prices) == 0:
return 0
first_buy = -1000000
fisrt_sell = 0
second_buy = -1000000
second_sell = 0
for i in prices:
first_buy = max(first_buy, -i)
fisrt_sell = max(fisrt_sell, first_buy + i)
second_buy = max(second_buy, fisrt_sell - i)
second_sell = max(second_sell,second_buy + i)
return second_sell
只能买卖n次
72.编辑距离
import static java.lang.Integer.min;
class Solution {
public int minDistance(String word1, String word2) {
int m = word1.length();
int n = word2.length();
int[][] dp = new int[m + 1][n + 1];
if(m == 0)
return n;
if(n == 0)
return m;
dp[0][0] = 0;
for(int i = 1; i <= m; i ++)
{
dp[i][0] = i;
}
for(int i = 1; i <= n; i ++)
{
dp[0][i] = i;
}
for(int i = 1; i <= m; i++)
for(int j = 1; j <= n; j++)
{
if(word1.charAt(i - 1) == word2.charAt(j - 1))
dp[i][j] = dp[i - 1][j - 1];
else
dp[i][j] = min(min(dp[i - 1][j], dp[i][j - 1]), dp[i - 1][j - 1]) + 1;
}
return dp[m][n];
}
}
本文使用 mdnice 排版