代码随想录 Day51 - 动态规划(十二)
 作者:jjn0703
- 2023-08-24  江苏
 本文字数:1321 字
阅读完需:约 4 分钟
作业题
309. 买卖股票的最佳时机含冷冻期
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-cooldown/description/
package jjn.daily;
import java.util.Scanner;
/** * @author Jjn * @since 2023/8/24 23:31 */public class LeetCode309 {    public int maxProfit(int[] prices) {        // 状态包含:持股/卖出且冷冻/卖出非冷冻        int[][] dp = new int[prices.length][3];        dp[0][0] = -prices[0];        dp[0][1] = 0;        dp[0][2] = 0;        for (int i = 1; i < prices.length; i++) {            // dp[i][0] - 持有股票            // 1.保留昨天买的股票            // 2. 卖出非冷冻期的股票            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][2] - prices[i]);            // dp[i][1]            // 卖出昨天购买的股票            dp[i][1] = dp[i - 1][0] + prices[i];            // dp[i][2]            // 1.昨天卖出,非冷冻            // 2. 昨天没卖出,非冷冻            dp[i][2] = Math.max(dp[i - 1][1], dp[i - 1][2]);        }        // 若最后一天依然持有股票,显然不是最佳解        return Math.max(dp[prices.length - 1][1], dp[prices.length - 1][2]);    }        public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        int total = scanner.nextInt();        int[] prices = new int[total];        for (int i = 0; i < total; i++) {            prices[i] = scanner.nextInt();        }        int maxProfit = new LeetCode309().maxProfit(prices);        System.out.println(maxProfit);    }}
复制代码
 714. 买卖股票的最佳时机含手续费
链接:https://leetcode.cn/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/
package jjn.daily;
import java.util.Scanner;
/** * @author Jjn * @since 2023/8/24 23:48 */public class LeetCode714 {    public int maxProfit(int[] prices, int fee) {        int[][] profit = new int[prices.length][2];        profit[0][0] = 0;        profit[0][1] = -prices[0];        for (int i = 1; i < prices.length; i++) {            // 已经持有股票,卖出去            profit[i][0] = Math.max(profit[i - 1][0], profit[i - 1][1] + prices[i] - fee);            profit[i][1] = Math.max(profit[i - 1][1], profit[i - 1][0] - prices[i]);        }        return profit[prices.length - 1][0];    }        public static void main(String[] args) {        Scanner scanner = new Scanner(System.in);        int fee = scanner.nextInt();        int total = scanner.nextInt();        int[] prices = new int[total];        for (int i = 0; i < total; i++) {            prices[i] = scanner.nextInt();        }        int maxProfit = new LeetCode714().maxProfit(prices, fee);        System.out.println(maxProfit);    }}
复制代码
 划线
评论
复制
发布于: 2023-08-24阅读数: 11
版权声明: 本文为 InfoQ 作者【jjn0703】的原创文章。
原文链接:【http://xie.infoq.cn/article/e8040703c6608afc039530bca】。
本文遵守【CC-BY 4.0】协议,转载请保留原文出处及本版权声明。
jjn0703
关注
Java工程师/终身学习者 2018-03-26 加入
USTC硕士/健身健美爱好者/Java工程师.










    
评论