added canCompleteCircuit
This commit is contained in:
@@ -17,3 +17,4 @@ add_subdirectory(jump)
|
||||
add_subdirectory(hindex)
|
||||
add_subdirectory(randomizedset)
|
||||
add_subdirectory(productExceptSelf)
|
||||
add_subdirectory(canCompleteCircuit)
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
FILE(GLOB_RECURSE SOURCES src/*.cpp)
|
||||
|
||||
add_executable(
|
||||
canCompleteCircuit
|
||||
${SOURCES}
|
||||
)
|
||||
@@ -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)
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -11,3 +11,4 @@ subdir('jump')
|
||||
subdir('hindex')
|
||||
subdir('randomizedset')
|
||||
subdir('productExceptSelf')
|
||||
subdir('canCompleteCircuit')
|
||||
|
||||
Reference in New Issue
Block a user