您的位置:首页 > Web前端

714[Medium]: Best Time to Buy and Sell Stock with Transaction Fee

2017-12-13 09:14 525 查看
Part1:题目描述

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] = 1Selling at prices[3] = 8Buying at prices[4] = 4Selling at prices[5] = 9The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.

Note:

0 < prices.length <= 50000
.
0 < prices[i] < 50000
.
0 <= fee < 50000
.
Part2:解题思路

  在第i天,价格为prices[i]时我们有3种操作:不作任何行动,买进,卖出可以选择。我们维护sell和notSell这2个变量,分别表示卖出和买进之后的最大获利,如果这2个值取一步的值则表示不作任何行动。对于每一个prices[i]只需要考虑如何通过上一步已计算出的sell和notSell得到当前的sell和notSell。

小说明:

  你首先能获得的一组具体值,决定了你的循环是从0->length还是length->0。因为在对price[i]这个值进行相关计算的时候,我们都需要保证计算中用到的值在之前已经计算过。本题中我们先获得第0天的时候的sell和notSell值,所以我们的循环是0->length。

Part3:代码

#include<iostream>
#include<vector>
#include<algorithm>

using namespace std;

int maxProfit(vector<int>& prices, int fee) {
int sell = 0;
int notSell = 0;
int length = prices.size();
for (int i = 0; i < length; i++) {
if (i == 0) {
sell = 0;
notSell = 0 - prices[i];
} else {
// 在当前这个价格prices[i]的时候,不作任何行动or卖掉
sell = max(sell, notSell+prices[i]-fee);
// 在当前这个价格prices[i]的时候,不作任何行动or买进
notSell = max(notSell, sell-prices[i]);
}
}
return sell;
}

int main() {
int num;
cin >> num;
vector<int> prices;
for (int i = 0; i < num; i++) {
int temp;
cin >> temp;
prices.push_back(temp);
}
int fee;
cin >> fee;
cout << maxProfit(prices, fee) << endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 动态规划