题目描述
给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
输入输出示例
贪心算法求解思路
个人感觉,虽然这道题目为中等难度,但比同类型简单难度的一道题还easy!
力扣121-买卖股票的最佳时机1——贪心算法https://blog.csdn.net/weixin_44564247/article/details/125659955这道题的贪心思路其实就是今天的股价和昨天的作比较,如果比昨天的价格高就出,也就是满足 (prices[i] - prices[i-1]) > 0 就行。然后将获得利润累加即可。
代码
class Solution {
public int maxProfit(int[] prices) {
int res = 0;
for(int i = 1; i < prices.length; i++){
if(prices[i] > prices[i-1]){
res += (prices[i] - prices[i-1]);
}
}
return res;
}
}
动态规划求解思路
感觉官方的这个题解写的比较清晰,容易理解。
代码
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int[][] dp = new int[n][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for(int i = 1; i < n; 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[n-1][0];
}
}