Re: [闲聊] 每日LeetCode

楼主: Rushia (みけねこ的鼻屎)   2023-06-22 11:03:33
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/
714. Best Time to Buy and Sell Stock with Transaction Fee
给你一个阵列 prices 表示股票每天的价钱,一个 fee 表示每次卖掉股票的手续费
,一天只能持有一个股票而且进行一次买或卖,求股票的最大收益。
Example 1:
Input: prices = [1,3,2,8,4,9], fee = 2
Output: 8
Explanation: The maximum profit can be achieved by:
- Buying at prices[0] = 1
- Selling at prices[3] = 8
- Buying at prices[4] = 4
- Selling at prices[5] = 9
The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
Example 2:
Input: prices = [1,3,7,5,10,3], fee = 3
Output: 6
思路:
1.用DP来动态的纪录买卖状态转移,buy = 当天持有股票, sell = 当天不持有股票
2.当天持有股票只可能是:
一、前一天持有股票,今天不买卖
二、前一天不持有股票,今天买入
当天不持有股票只可能是:
一、前一天不持有股票,今天不买卖
二、前一天持有股票,今天卖掉
状态转移方程:
buy[i] = Max(buy[i-1], sell[i-1] - prices[i])
sell[i] = Max(sell[i-1], buy[i-1] + prices[i] - fee)
(卖的当下要多扣手续费)
3.最后取第 n 天的sell即可,最后一天不持有股票一定是最佳收益。
Java Code:

Links booklink

Contact Us: admin [ a t ] ucptt.com