added candy
This commit is contained in:
@@ -18,3 +18,4 @@ add_subdirectory(hindex)
|
||||
add_subdirectory(randomizedset)
|
||||
add_subdirectory(productExceptSelf)
|
||||
add_subdirectory(canCompleteCircuit)
|
||||
add_subdirectory(candy)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
SUBDIRS := canJump jump majorityelement maxprofit maxprofit2 rmdupfromsortedarray rmdupfromsortedarray2 rotate twopointers hindex randomizedset productExceptSelf canCompleteCircuit
|
||||
SUBDIRS := canJump jump majorityelement maxprofit maxprofit2 rmdupfromsortedarray rmdupfromsortedarray2 rotate twopointers hindex randomizedset productExceptSelf canCompleteCircuit candy
|
||||
|
||||
all: $(SUBDIRS)
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
FILE(GLOB_RECURSE SOURCES src/*.cpp)
|
||||
|
||||
add_executable(
|
||||
candy
|
||||
${SOURCES}
|
||||
)
|
||||
@@ -0,0 +1,17 @@
|
||||
CXX = g++
|
||||
CFLAGS = -Wall -g -std=c++20
|
||||
SRCS = $(wildcard src/*/*.cpp src/*.cpp)
|
||||
OBJS = $(SRCS:.cpp=.o)
|
||||
TARGET = candy
|
||||
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('candy', 'src/main.cpp', install: true)
|
||||
@@ -0,0 +1,19 @@
|
||||
#include <numeric>
|
||||
#include <vector>
|
||||
|
||||
inline int candy(std::vector<int> &ratings) {
|
||||
int n = ratings.size();
|
||||
if (n == 0) return 0;
|
||||
std::vector<int> candies(n, 1);
|
||||
for (int i = 1; i < n; i++) {
|
||||
if (ratings[i] > ratings[i - 1]) {
|
||||
candies[i] = candies[i - 1] + 1;
|
||||
}
|
||||
}
|
||||
for (int i = n - 2; i >= 0; i--) {
|
||||
if (ratings[i] > ratings[i + 1]) {
|
||||
candies[i] = std::max(candies[i], candies[i + 1] + 1);
|
||||
}
|
||||
}
|
||||
return std::accumulate(candies.begin(), candies.end(), 0);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
#include <cassert>
|
||||
#include <vector>
|
||||
#include "candy.hpp"
|
||||
|
||||
int main() {
|
||||
std::vector<int> ratings = {1, 0, 2};
|
||||
int output = candy(ratings);
|
||||
assert(output == 5);
|
||||
|
||||
ratings = {1, 2, 2};
|
||||
output = candy(ratings);
|
||||
assert(output == 4);
|
||||
return 0;
|
||||
}
|
||||
@@ -12,3 +12,4 @@ subdir('hindex')
|
||||
subdir('randomizedset')
|
||||
subdir('productExceptSelf')
|
||||
subdir('canCompleteCircuit')
|
||||
subdir('candy')
|
||||
|
||||
Reference in New Issue
Block a user