added candy

This commit is contained in:
wt
2026-04-09 16:01:16 +07:00
parent c15b4b66e0
commit d2032ea77d
8 changed files with 60 additions and 1 deletions
+1
View File
@@ -18,3 +18,4 @@ add_subdirectory(hindex)
add_subdirectory(randomizedset) add_subdirectory(randomizedset)
add_subdirectory(productExceptSelf) add_subdirectory(productExceptSelf)
add_subdirectory(canCompleteCircuit) add_subdirectory(canCompleteCircuit)
add_subdirectory(candy)
+1 -1
View File
@@ -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) all: $(SUBDIRS)
+6
View File
@@ -0,0 +1,6 @@
FILE(GLOB_RECURSE SOURCES src/*.cpp)
add_executable(
candy
${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 = 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)
+1
View File
@@ -0,0 +1 @@
executable('candy', 'src/main.cpp', install: true)
+19
View File
@@ -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);
}
+14
View File
@@ -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;
}
+1
View File
@@ -12,3 +12,4 @@ subdir('hindex')
subdir('randomizedset') subdir('randomizedset')
subdir('productExceptSelf') subdir('productExceptSelf')
subdir('canCompleteCircuit') subdir('canCompleteCircuit')
subdir('candy')