diff --git a/CMakeLists.txt b/CMakeLists.txt index 760f19d1..f9bc6685 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -413,6 +413,7 @@ add_task(minimum-distance-between-bst-nodes) add_task(minimum-falling-path-sum) add_task(minimum-flips-to-make-a-or-b-equal-to-c) add_task(minimum-genetic-mutation) +add_task(minimum-hours-of-training-to-win-a-competition) add_task(minimum-insertion-steps-to-make-a-string-palindrome) add_task(minimum-jumps-to-reach-home) add_task(minimum-limit-of-balls-in-a-bag) diff --git a/solutions/minimum-hours-of-training-to-win-a-competition/CMakeLists.txt b/solutions/minimum-hours-of-training-to-win-a-competition/CMakeLists.txt new file mode 100644 index 00000000..0690dcc7 --- /dev/null +++ b/solutions/minimum-hours-of-training-to-win-a-competition/CMakeLists.txt @@ -0,0 +1 @@ +add_catch(test_minimum_hours_of_training_to_win_a_competition test.cpp) diff --git a/solutions/minimum-hours-of-training-to-win-a-competition/solution.hpp b/solutions/minimum-hours-of-training-to-win-a-competition/solution.hpp new file mode 100644 index 00000000..86540037 --- /dev/null +++ b/solutions/minimum-hours-of-training-to-win-a-competition/solution.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include +#include + +class Solution { +public: + static int minNumberOfHours(int initialEnergy, int initialExperience, + const std::vector &energy, + const std::vector &experience) { + return trainEnergy(initialEnergy, energy) + + trainExperience(initialExperience, experience); + } + +private: + static int trainEnergy(int initialEnergy, const std::vector &energy) { + const auto sum = std::accumulate(energy.begin(), energy.end(), 0); + return std::max(0, sum - initialEnergy + 1); + } + + static int trainExperience(int initialExperience, + const std::vector &experience) { + int max = 0, prev = 0; + for (auto e : experience) { + max = std::max(max, e - prev); + prev += e; + } + return std::max(0, max - initialExperience + 1); + } +}; diff --git a/solutions/minimum-hours-of-training-to-win-a-competition/test.cpp b/solutions/minimum-hours-of-training-to-win-a-competition/test.cpp new file mode 100644 index 00000000..0ab78642 --- /dev/null +++ b/solutions/minimum-hours-of-training-to-win-a-competition/test.cpp @@ -0,0 +1,37 @@ +#include + +#include + +TEST_CASE("Simple") { + struct TestCase { + int initialEnergy; + int initialExperience; + std::vector energy; + std::vector experience; + int expected; + }; + + std::vector test_cases{ + { + .initialEnergy = 5, + .initialExperience = 3, + .energy{1, 4, 3, 2}, + .experience{2, 6, 3, 1}, + .expected = 8, + }, + { + .initialEnergy = 2, + .initialExperience = 4, + .energy{1}, + .experience{3}, + .expected = 0, + }, + }; + + for (const auto &[initialEnergy, initialExperience, energy, experience, + expected] : test_cases) { + const auto actual = Solution::minNumberOfHours( + initialEnergy, initialExperience, energy, experience); + REQUIRE(expected == actual); + } +}