added canCompleteCircuit

This commit is contained in:
wt
2026-04-09 12:26:33 +07:00
parent 5d53e6ea69
commit c15b4b66e0
8 changed files with 59 additions and 1 deletions
@@ -0,0 +1,16 @@
#include <vector>
inline int canCompleteCircuit(std::vector<int> &gas, std::vector<int> &cost) {
int total_tank = 0;
int curr_tank = 0;
int start = 0;
for (int i = 0; i < int(gas.size()); i++) {
total_tank += gas[i] - cost[i];
curr_tank += gas[i] - cost[i];
if (curr_tank < 0) {
start = i + 1;
curr_tank = 0;
}
}
return total_tank >= 0 ? start : -1;
}
+16
View File
@@ -0,0 +1,16 @@
#include <cassert>
#include <vector>
#include "canCompleteCircuit.hpp"
int main() {
std::vector<int> gas = {1, 2, 3, 4, 5};
std::vector<int> cost = {3, 4, 5, 1, 2};
int output = canCompleteCircuit(gas, cost);
assert(output == 3);
gas = {2, 3, 4};
cost = {3, 4, 3};
output = canCompleteCircuit(gas, cost);
assert(output == -1);
return 0;
}