714. Best Time to Buy and Sell Stock with Transaction Fee

来源:互联网 发布:莱昂纳德14总决赛数据 编辑:程序博客网 时间:2024/06/06 18:36

714. Best Time to Buy and Sell Stock with Transaction Fee

标签(空格分隔): leetcode array medium


题目

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 = 2Output: 8Explanation: 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.
  • 思路

    本题是个典型的股票题,由于股票可以买卖多次,因此我们定义两个变量:s0,s1;其中s0和s1的定义如下:

    • s0:代表买完股票的利润
    • s1:代表卖完股票的利润

    更新规则:
    update s0 by selling the stock from s1, so s0 = max(s0, s1+p);
    update s1 by buying the stock from s0, so s1 = max(s1, s0-p-fee);

    代码

    class Solution {public:    int maxProfit(vector<int>& prices, int fee) {        int s0=0,s1=INT_MIN,tmp;        for(auto p:prices)        {            tmp=s0;            s0=max(s0,s1+p);            s1=max(s1,tmp-p-fee);        }        return s0;    }};
    阅读全文
    '); })();
    1 0
    原创粉丝点击
    热门IT博客
    热门问题 老师的惩罚 人脸识别 我在镇武司摸鱼那些年 重生之率土为王 我在大康的咸鱼生活 盘龙之生命进化 天生仙种 凡人之先天五行 春回大明朝 姑娘不必设防,我是瞎子 半球热水器打不着火 半球电压力锅批发 半球电压力锅好不好 半球抽油烟机 半球电压力锅价格 半球微电脑光波炉 半球电压力锅e4 让半球怎么算 半球红外线光波炉 半球液化气灶 地球东西半球 半球电热水壶怎么样 半球高压锅e4 半球电压力锅 e4 半球电压力锅4l 半球电压力锅配件 半球是什么牌子 半球电烧水壶怎么样 半球智能电压力锅 开水壶 烧水器 电茶壶 电热 电热壶 热水瓶 烧水 煮水壶 开水煲 电壶 电热水瓶 快壶 怎样烧水没有水垢 煮茶器 电烧水壶什么牌子好 玻璃烧水壶 304不锈钢烧水壶 美的烧水壶 电烧水杯 荣事达豆浆机 苏泊尔豆浆机 半球体