LeetCode题目:714. 买卖股票的最佳时机含手续费

题目

题目链接:https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
题目解析:

  1. 主要是维护今天的股票买的利润m和今天的股票不买的利润n这两个变量
  2. 首先先将两个变量初始化,n = 0 ,m = -price[0];
  3. 然后从后一天开始遍历
    • 先判断,如果今天将股票卖出去的利润会不会比之前的利润高
    • 然后判断,如果买今天的股票不然买之前的股票会不会更划算
      在这里插入图片描述

代码

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;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_41816516/article/details/106696790
今日推荐