codekofi
← All problems

Problem 9

Medium35 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 best = 0;
6 while (left < right) {
7 int height = min(nums[left], nums[right]);
8 int area = height * (right - left);
9 if (area > best) best = area;
10 if (nums[left] < nums[right]) left++;
11 else right--;
12 }
13 return best;
14}

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.