codekofi
← All problems

Problem 7

Hard

1 · Worked examples

0 / 4

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 4 outputs correctly.

The accepted solution

1int solution(const vector<int>& nums) {
2
3 if (nums.empty()) {
4 return 0;
5 }
6
7 int left = 0;
8 int right = nums.size() - 1;
9 int leftMax = nums[left];
10 int rightMax = nums[right];
11 int ans = 0;
12
13 while (left < right) {
14
15 if (leftMax < rightMax) {
16
17 left++;
18
19 if (nums[left] > leftMax) {
20 leftMax = nums[left];
21 }
22
23 ans += leftMax - nums[left];
24
25 } else {
26
27 right--;
28
29 if (nums[right] > rightMax) {
30 rightMax = nums[right];
31 }
32
33 ans += rightMax - nums[right];
34 }
35 }
36
37 return ans;
38}

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.