题目
题目链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
题目解析:
- 主要是维护今天的股票买的利润m和今天的股票不买的利润n这两个变量
- 首先先将两个变量初始化,n = 0 ,m = -price[0];
- 然后从后一天开始遍历
- 先判断,如果今天将股票卖出去的利润会不会比之前的利润高
- 然后判断,如果买今天的股票不然买之前的股票会不会更划算
代码
class Solution {
public int maxProfit(int[] prices, int fee) {
//如果第一天不买股票
int no = 0;
//如果第一天买股票
int buy = 0-prices[0];
for(int i=1;i<prices.length;i++) {
no = Math.max(no, buy+prices[i]-fee);
buy = Math.max(buy,no-prices[i]);
}
return no;
}
}