您的位置:首页 > Web前端

LeetCode Best Time to Buy and Sell Stock with Transaction Fee

2017-12-28 03:37 495 查看
原题链接在这里:https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/description/

题目:

Your are given an array of integers
prices
, for which the
i
-th element is the price of a given stock on day
i
; and a non-negative integer
fee
representing a transaction fee.

You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction. You may not buy more than 1 share of a stock at a time (ie. you must sell the stock share before you buy again.)

Return the maximum profit you can make.

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.

Note:

0 < prices.length <= 50000
.

0 < prices[i] < 50000
.

0 <= fee < 50000
.

题解:

T[i][k][0] 代表maximum profit that could be gained at the end of the i-th day with at most k transactions. 最后手上剩下0股stock.

递推公式就是

T[i][k][0] = max(T[i-1][k][0], T[i-1][k][1] + prices[i])
T[i][k][1] = max(T[i-1][k][1], T[i-1][k-1][0] - prices[i])

如果需要加上transaction fee就变成

T[i][k][0] = max(T[i-1][k][0], T[i-1][k][1] + prices[i])
T[i][k][1] = max(T[i-1][k][1], T[i-1][k][0] - prices[i] - fee)

买入时交fee.

最后肯定是卖掉手上的股票收益更多,所以返回T[i][k][0].

Time Complexity: O(n). n = prices.length.

Space: O(1).

AC Java:

1 class Solution {
2     public int maxProfit(int[] prices, int fee) {
3         int tIk0 = 0;
4         int tIk1 = Integer.MIN_VALUE;
5         for(int price : prices){
6             int preTransactionIk0 = tIk0;
7             tIk0 = Math.max(tIk0, tIk1+price);
8             tIk1 = Math.max(tIk1, tIk0-price-fee);
9         }
10         return tIk0;
11     }
12 }


类似Best Time to Buy and Sell Stock II.

买卖股票类题目都可以套用这个思路.

Reference: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/discuss/108870/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: