codekofi
← All problems

Problem 7

Hard45 XP

1 · Worked examples

0 / 4

Give it an input and say what you think comes back. It compiles and runs for real, so a wrong guess still shows you the answer — probe as much as you like. 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 if (nums.empty()) return 0;
3 int left = 0;
4 int right = nums.size() - 1;
5 int leftMax = nums[left];
6 int rightMax = nums[right];
7 int total = 0;
8 while (left < right) {
9 if (leftMax < rightMax) {
10 left++;
11 if (nums[left] > leftMax) leftMax = nums[left];
12 total += leftMax - nums[left];
13 } else {
14 right--;
15 if (nums[right] > rightMax) rightMax = nums[right];
16 total += rightMax - nums[right];
17 }
18 }
19 return total;
20}

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.