zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【算法/贪心算法/股票问题】题解+详细备注(共2题)

算法 详细 题解 贪心 股票 备注 问题
2023-09-11 14:20:02 时间

【算法/贪心算法/股票问题】题解+详细备注(共2题)

122.买卖股票的最佳时机II

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int n = prices.size();

        int result{};
        // 贪心求解:只要当前价格>前一天价格,就进行一次买卖
        for(int i{};i<n-1;++i){
            if(prices[i+1] - prices[i] > 0){
                result+=(prices[i+1]-prices[i]);
            }
        }

        return result;
    }
};

714.买卖股票的最佳时机含手续费

class Solution {
public:
    int maxProfit(vector<int>& prices, int fee) {
        int n = prices.size();

        int result{};
        int minPrices{prices[0]}; // 记录最小价格
        for(int i = 1;i<n;++i){
            if(prices[i] < minPrices) minPrices = prices[i];
			
            if(prices[i] > minPrices && prices[i] <= minPrices+ fee){
                continue;
            }
			// 贪心,只要遇到当前价格大于最小价格和手续费的和,就进行买卖(不是真正的买卖)
            if(prices[i] - minPrices > fee){
                result +=(prices[i] -minPrices - fee);
                minPrices=prices[i] - fee; // 要让minPrice = prices[i] - fee;,这样在明天收获利润的时候,才不会多减一次手续费!
            }
        }

        return result;
    }
};