First I thought it should is solved using DP, and I gave a standard O (n^2) Solution:
#include <iostream>#include<vector>#include<algorithm>#include<numeric>using namespacestd;#defineREP (i, S, N) for (int i = s; i < n; i + +)typedefLong LongLL; LL Calc (Vector<LL> &inch) {size_t len=inch. Size (); LL ret=0; /*//Dp[i][onhand] vector<vector<ll>> dp (len, vector<ll> (len + 1, std::numeric_limits<ll& Gt;::min ())); Dp[0][0] = 0; No action dp[0][1] =-in[0]; Buy Rep (i, 1, Len) Rep (j, 0, I + 1) {//Choice 1:buy dp[i][j + 1] = Std::max (dp[i][j + 1], DP[I-1][J]-in[i]); Choice 2:no action Dp[i][j] = Std::max (Dp[i][j], dp[i-1][j]); Choice 3:sell All if (J > 0) dp[i][0] = Std::max (dp[i][0], In[i] * j + dp[i-1][j]); } ret = *std::max_element (Dp[len-1].begin (), Dp[len-1].end ()); */Vector<LL> Pre (len +1, std::numeric_limits<ll>:: Min ()); pre[0] =0; pre[1] = -inch[0]; Vector<LL> Now (len +1, std::numeric_limits<ll>:: Min ()); Vector<LL> *ppre = &pre, *pnow = &Now ; REP (i,1, Len) {REP (J,0, i +1) { //Choice 1:buy(*pnow) [J +1] = Std::max ((*pnow) [j +1], (*ppre) [j]-inch[i]); //Choice 2:no Action(*pnow) [j] = Std::max ((*pnow) [j], (*ppre) [j]); //Choice 3:sell All if(J >0) (*pnow) [0] = Std::max ((*pnow) [0],inch[i] * j + (*ppre) [j]); } //SwapStd::swap (Ppre, Pnow); (*pnow). Assign (len +1, std::numeric_limits<ll>:: Min ()); } ret= *std::max_element ((*ppre). Begin (), (*ppre). end ()); returnret;}intMain () {intT CIN >>T; while(t--) { intN CIN >>N; Vector<LL>inch(n); REP (i,0, N) Cin >>inch[i]; cout<< Calc (inch) <<Endl; } return 0;}
But all TLE. So there was must be a O (n) solution, and there is. What's better than a standard DP in cerntain cases? Greedy.
#include <iostream>#include<vector>#include<algorithm>#include<numeric>using namespacestd;#defineREP (i, S, N) for (int i = s; i < n; i + +)typedefLong LongLL; LL Calc (Vector<LL> &inch) {size_t len=inch. Size (); LL ret=0; Std::reverse (inch. Begin (),inch. End ()); LL Peak= -1; REP (i,0, Len) { if(inch[I] >Peak) {Peak=inch[i]; } Else{ret+ = peak-inch[i]; } } returnret;}intMain () {intT CIN >>T; while(t--) { intN CIN >>N; Vector<LL>inch(n); REP (i,0, N) Cin >>inch[i]; cout<< Calc (inch) <<Endl; } return 0;}
Hackerrank-"Stock maximize"