1 条题解

  • 0
    @ 2025-11-13 19:42:34
    • 效仿 买卖股票2
    • 此题最多可以买卖 22 次,那么我们需要 44 个变量
    • buy1, sell1, buy2, sell2
    #include <bits/stdc++.h>
    using namespace std;
    
    int maxProfit(vector<int>& a) {
        int n = a.size(), inf = 1000000000;
        
        // buy1 : 第 1 次买完股票后手里的钱, 初始没买过股票, 所以 buy 是 -inf
        // sell1: 第 1 次卖完股票后手里的钱, 初始没有股票, 所以 sell 是 0
        // 同理: buy2, sell2
        int buy1 = -inf, buy2 = -inf;
        int sell1 = 0, sell2 = 0;
        for (int i = 0; i < n; i++) {
            
            // 买股票, 手里的钱会变少
            buy1  = max(buy1,  0 - a[i]);  // max(啥也不干, 买股票)
            
            // 卖股票, 手里的钱会变多
            sell1 = max(sell1, buy1  + a[i]);  // max(啥也不干, 卖股票)
            
            // 第 2 笔交易的情况
            buy2  = max(buy2,  sell1 - a[i]);  // max(啥也不干, 买股票)
            sell2 = max(sell2, buy2  + a[i]);  // max(啥也不干, 卖股票)
        }
        return sell2;
    }
    
    int main() {	
        ios::sync_with_stdio(false);
        cin.tie(0); cout.tie(0);
        
        int n;
        cin >> n;
        vector<int> a(n);
        for (int i = 0; i < n; i++) cin >> a[i];
        cout << maxProfit(a) << '\n';
        return 0;
    }
    
    • 1

    【普及】买卖股票的最佳时机_3

    信息

    ID
    170
    时间
    200ms
    内存
    256MiB
    难度
    1
    标签
    递交数
    45
    已通过
    31
    上传者