Leetcode714. Best Time to Buy and Sell Stock with Transaction Fee (算法分析week13)

来源:互联网 发布:机器人编程入门学生 编辑:程序博客网 时间:2024/06/16 09:22

Best Time to Buy and Sell Stock with Transaction Fee

题目来源:https://leetcode.com/problemset/algorithms/

-题目描述-
-算法分析-
-代码实现-

题目描述

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.

算法分析

题目的目的是给定一数组prices[n],prices[i]为第i天的股票的价格,计算通过交易股票可以获得最大利润。(一个人手中只能持有一只股票,想要再买必须先卖掉手中的股票。买一次股票的花费为fee。)
通过定义两个数组sell和hold。sell[i]表示第i天卖掉股票得到的最大利润。hold[i]表示第i天持有股票时的最大利润。
第i天卖掉股票得到的最大利润为前一天卖掉股票的最大利润和当天卖掉股票的利润的较大值。
sell[i]=max{sell[i-1], hold[i-1]+prices[i]-fee};
第i天持有股票的最大利润为前一天持有股票时的最大利润和今天买入股票后的利润的较大值。
hold[i]=max{hold[i-1], sell[i-1]-prices[i]};
通过股票交易可以获得的最大利润为最后一天已经卖掉股票的最大利润即sell[n].

代码实现

@requires_authorizationclass Solution {public:    int maxProfit(vector<int>& prices, int fee) {        int n = prices.size();        int* buy = new int[n+1];        int* sell = new int[n+1];        buy[0] = 0 - prices[0];        sell[0] = 0;        for (int i = 1; i < n; i++) {            buy[i] = max(buy[i - 1], sell[i - 1] - prices[i]);            sell[i] = max(sell[i - 1], buy[i - 1] + prices[i] - fee);        }        return sell[n - 1];    }};
阅读全文
0 0