codekofi
← All problems

Problem 140

Medium

1 · Worked examples

0 / 3

Type an input and write what you think is the output . Each problem is converted to Web Assembly, so any possible input will show the corresponding output. Only correct predictions count.

solution()
returns

2 · Which problem is it?

Locked until you have predicted 3 outputs correctly.

The accepted solution

1int solution(const vector<int>& prices) {
2
3 int n = prices.size();
4
5 if (n == 0) {
6 return 0;
7 }
8
9 vector<int> hold(n, 0);
10 vector<int> sold(n, 0);
11 vector<int> rest(n, 0);
12
13 hold[0] = -prices[0];
14 sold[0] = 0;
15 rest[0] = 0;
16
17 for (int i = 1; i < n; i++) {
18
19 hold[i] = max(hold[i - 1], rest[i - 1] - prices[i]);
20 sold[i] = hold[i - 1] + prices[i];
21 rest[i] = max(rest[i - 1], sold[i - 1]);
22 }
23
24 return max(sold[n - 1], rest[n - 1]);
25}

Names have been stripped. The signature is the only clue you get for free. Compiled as C++20 with the standard headers and using namespace std; already in scope.