codekofi
← All problems

Problem 122

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>& gas, const vector<int>& cost) {
2
3 int n = gas.size();
4
5 int total = 0;
6 int tank = 0;
7 int start = 0;
8
9 for (int i = 0; i < n; i++) {
10
11 int gain = gas[i] - cost[i];
12
13 total += gain;
14 tank += gain;
15
16 if (tank < 0) {
17 start = i + 1;
18 tank = 0;
19 }
20 }
21
22 if (total < 0) {
23 return -1;
24 }
25
26 return start;
27}

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.