AcWing_1055 股票买卖II(模拟、贪心)

AcWing

1055. 股票买卖II

state表示下一个操作是买还是卖。如果当前需要买,而且第二天的价格会比今天便宜,那么今天不操作;如果当前需要卖,而且第二天的价格会比今天贵,那么今天不操作;否则买/卖,并更改当前的state.

对最后一天特判,如果当前手中没有股票,那么就不买,因为即使买了也不能获利了;如果当前手中有股票,那么将其卖掉。

#include <bits/stdc++.h>
using namespace std;
int n;
const int N = 100010;
int a[N];
bool state;    // 下一个操作是买/卖
int main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    cin >> n;
    for(int i = 1; i <= n; i ++) cin >> a[i];
    int res = 0, pr;
    for(int i = 1; i <= n - 1; i ++){
        if(!state && a[i] > a[i + 1]) continue;
        if(state && a[i] < a[i + 1]) continue;
        if(!state) pr = a[i], state = !state;
        else res += (a[i] - pr), state = !state;
    }
    // 特判最后一天
    if(state) res += (a[n] - pr);
    cout << res;
    return 0;
}