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
+1
View File
@@ -17,3 +17,4 @@ add_subdirectory(jump)
add_subdirectory(hindex)
add_subdirectory(randomizedset)
add_subdirectory(productExceptSelf)
add_subdirectory(canCompleteCircuit)
+1 -1
View File
@@ -1,4 +1,4 @@
SUBDIRS := canJump jump majorityelement maxprofit maxprofit2 rmdupfromsortedarray rmdupfromsortedarray2 rotate twopointers hindex randomizedset productExceptSelf
SUBDIRS := canJump jump majorityelement maxprofit maxprofit2 rmdupfromsortedarray rmdupfromsortedarray2 rotate twopointers hindex randomizedset productExceptSelf canCompleteCircuit
all: $(SUBDIRS)
+6
View File
@@ -0,0 +1,6 @@
FILE(GLOB_RECURSE SOURCES src/*.cpp)
add_executable(
canCompleteCircuit
${SOURCES}
)
+17
View File
@@ -0,0 +1,17 @@
CXX = g++
CFLAGS = -Wall -g -std=c++20
SRCS = $(wildcard src/*/*.cpp src/*.cpp)
OBJS = $(SRCS:.cpp=.o)
TARGET = canCompleteCircuit
CROSS_COMPILE =
all: $(TARGET)
$(TARGET): $(OBJS)
$(CROSS_COMPILE)$(CXX) $(LDFLAGS) $^ -o $@ $(LIBS)
%.o: %.cpp
$(CROSS_COMPILE)$(CXX) $(CFLAGS) $(INCLUDES) -c $< -o $@
clean:
rm -f $(OBJS) $(TARGET)
+1
View File
@@ -0,0 +1 @@
executable('canCompleteCircuit', 'src/main.cpp', install: true)
@@ -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;
}
+1
View File
@@ -11,3 +11,4 @@ subdir('jump')
subdir('hindex')
subdir('randomizedset')
subdir('productExceptSelf')
subdir('canCompleteCircuit')