121. 买卖股票的最佳时机
给定一个数组 prices ,它的第 i 个元素 prices[i] 表示一支给定股票第 i 天的价格。
你只能选择 某一天 买入这只股票,并选择在 未来的某一个不同的日子 卖出该股票。设计一个算法来计算你所能获取的最大利润。
返回你可以从这笔交易中获取的最大利润。如果你不能获取任何利润,返回 0 。
示例 1:
输入:[7,1,5,3,6,4]
输出:5
解题思路
按照贪心的思路,我们只要找到两天的股票价格差值最大,那么获得的利润就是最大的。
也可以采用动态规划的思路来分析:
确定dp数组及下标含义
dp[i][0] :表示第i天持有股票所能获得最多现金。初始现金为0,第i天买入股票那么第i天拥有的现金是 -prices[i]。
dp[i][1] :表示第i天不持有股票所能获得最多现金。
确定递推公式
如果第i天持有股票,所得金额可以由两种情况推导:
第i-1天持有股票,第i天仍保持,所以dp[i][0] = dp[i-1][0]
第i天持有股票,所得金额要减去今天买入的-prices[i]
取最大值:dp[i][0] = max(dp[i-1][0],-prices[i]);
如果第i天不持有股票,所得金额可以由两种情况推导:
第i-1天就不持有股票,那么保持现状,所得金额 dp[i][1] = dp[i-1][1]
第i天卖出股票,所得现金就是按照今天股票价格卖出后的金额:dp[i][1] = dp[i-1][0] + prices[i]
dp数组初始化
从递推公式可知,推导的基础在于知道dp[0][0]和dp[0][1].
dp[0][0] = - prices[0]
dp[0][1] = 0
确定遍历顺序
从前向后遍历即可
代码示例-java
贪心
class Solution {
public int maxProfit(int[] prices) {
// 找到一个最小的买入点
int low = Integer.MAX_VALUE;
// res ,用来记录最大差值
int res = 0;
for(int i=0;i<prices.length;i++){
low = Math.min(prices[i],low);
res = Math.max(prices[i]-low,res);
}
return res;
}
}
动态规划
class Solution {
public int maxProfit(int[] prices) {
if(prices==null||prices.length==0) return 0;
int len = prices.length;
// 定义dp数组
int[][] dp = new int[len][2];
// 初始化
dp[0][0] = -prices[0];
dp[0][1] = 0;
for(int i=1;i<len;i++){
dp[i][0] = Math.max(dp[i-1][0],-prices[i]);
dp[i][1] = Math.max(dp[i-1][1],dp[i-1][0]+prices[i]);
}
return dp[len-1][1];
}
}
122.买卖股票的最佳时机II
给定一个数组,它的第 i 个元素是一支给定股票第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你可以尽可能地完成更多的交易(多次买卖一支股票)。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例 1:
输入: [7,1,5,3,6,4]
输出: 7
解释: 在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5-1 = 4。随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6-3 = 3 。
解题思路
本题与121非常相似,但也有不同,本题可以多次买入卖出,并且在买入新的之前需要卖掉之前的股票。
反应到递推公式上主要体现在如下不同:
确定递推公式:
如果第i天持有股票,所得金额可以由两种情况推导:
第i-1天持有股票,第i天仍保持,所以dp[i][0] = dp[i-1][0]
第i天持有股票即dp[i][0],如果是第i天买入股票,所得现金就是昨天不持有股票的所得现金 减去 今 天的股票价格 即:dp[i - 1][1] - prices[i]。
代码示例-java
贪心
class Solution {
public int maxProfit(int[] prices) {
int result = 0;
for(int i=0;i<prices.length-1;i++){
// 只收集正向利润
if(prices[i+1]-prices[i]>0){
result += prices[i+1] - prices[i];
}
}
return result;
}
}
动态规划
class Solution {
public int maxProfit(int[] prices) {
if(prices==null||prices.length==0) return 0;
int len = prices.length;
// 定义dp数组
int[][] dp = new int[len][2];
// 初始化
dp[0][0] = -prices[0];
dp[0][1] = 0;
for(int i=1;i<len;i++){
dp[i][0] = Math.max(dp[i-1][0],dp[i-1][1]-prices[i]);
dp[i][1] = Math.max(dp[i-1][1],dp[i-1][0]+prices[i]);
}
return dp[len-1][1];
}
}