package com.company.test.买卖股票的最好时机2;
/**
* @author xienl
* @description 买卖股票的最好时机
* @date 2022/9/1
*/
public class Solution {
public static void main(String[] args) {
Solution solution = new Solution();
}
/**
* 动态规划
* @param prices
* @return
*/
public int maxProfit (int[] prices) {
// write code here
int[][] dp = new int[prices.length][2];
// 0 代表不持有股票, 1代表持有股票
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < prices.length; 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[prices.length - 1][0];
}
/**
* 贪心, 只需要计算当天是否是比前一天便宜,如果便宜就直接卖出
* @param prices
* @return
*/
public int maxProfit2 (int[] prices) {
// write code here
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;
}
}
牛客网:NC134 买卖股票的最好时机(二)
最新推荐文章于 2024-10-02 23:40:03 发布