【ACWing】1058. Stock trading V

Subject address:

https://www.acwing.com/problem/content/1060/

Given a length of NNN of the array, the arrayiii numbers indicate that a given stock is in theiii- day price. Design an algorithm to calculate the maximum profit. Under the following constraints, you can complete as many transactions as possible (buying and selling a stock multiple times): You cannot participate in multiple transactions at the same time (you must sell the previous stock before buying again). After selling the stock, you cannot buy the stock the next day (ie, the freezing period is1 11 day).

Input format: the
first line contains the integer NNN represents the length of the array. The second line containsNNN no more than10000 100001 0 0 0 0 is a positive integer that represents a complete array.

Output format:
output an integer, representing the maximum profit.

Data range:
1 ≤ N ≤ 1 0 5 1≤N≤10^51N105

The idea is dynamic programming. You can use a state machine to simulate the entire process. Set three states, namely holding, selling, and freezing. Let f [i] [0, 1, 2] f[i][0,1,2]f[i][0,1,2 ] respectively represent theiiThe maximum profit in the three states at the end of day i , and setiii- day stock price isp [i] p[i]p [ i ] , there are:
1. Today’s holding can be transferred from yesterday’s holding and yesterday’s freezing, thenf [i] [0] = max ⁡ {f [i − 1] [0], f [ i − 1] [2] − p [i]} f[i][0]=\max\{f[i-1][0],f[i-1][2]-p[i]\ }f[i][0]=max{ f[i1][0],f[i1][2]p [ i ] } ;
2. Today’s selling can be transferred from yesterday’s holding, sof [i] [1] = f [i − 1] [0] + p [i] f[i][1] =f[i-1][0]+p[i]f[i][1]=f[i1][0]+p [ i ] ;
3. Today’s freezing can be transferred from yesterday’s freezing or yesterday’s selling, sof [i] [2] = max ⁡ {f [i − 1] [2], f [i − 1] [ 1]} f[i][2]=\max\{f[i-1][2],f[i-1][1]\}f[i][2]=max{ f[i1][2],f[i1 ] [ 1 ] } .
Finally returnmax ⁡ {f [n] [1], f [n] [2]} \max\{f[n][1],f[n][2]\}max{ f[n][1],f [ n ] [ 2 ] } . code show as below:

#include <iostream>
using namespace std;

const int N = 1e5 + 10;
int n;
int a[N], hold[N], sell[N], cool[N];

int main() {
    
    
    cin >> n;
    for (int i = 1; i <= n; i++) {
    
    
        cin >> a[i];
    }

    hold[0] = sell[0] = -1e9;
    for (int i = 1; i <= n; i++) {
    
    
        hold[i] = max(hold[i - 1], cool[i - 1] - a[i]);
        sell[i] = hold[i - 1] + a[i];
        cool[i] = max(cool[i - 1], sell[i - 1]);
    }

    cout << max(sell[n], cool[n]) << endl;

    return 0;
}

Time and space complexity O (N) O(N)O ( N )

Guess you like

Origin blog.csdn.net/qq_46105170/article/details/114427343