Skip to content

Commit

Permalink
Minimum Hours of Training to Win a Competition
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Oct 17, 2023
1 parent 39fe388 commit d46cc2b
Show file tree
Hide file tree
Showing 4 changed files with 69 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_minimum_hours_of_training_to_win_a_competition test.cpp)
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
#pragma once

#include <numeric>
#include <vector>

class Solution {
public:
static int minNumberOfHours(int initialEnergy, int initialExperience,
const std::vector<int> &energy,
const std::vector<int> &experience) {
return trainEnergy(initialEnergy, energy) +
trainExperience(initialExperience, experience);
}

private:
static int trainEnergy(int initialEnergy, const std::vector<int> &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<int> &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);
}
};
37 changes: 37 additions & 0 deletions solutions/minimum-hours-of-training-to-win-a-competition/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
struct TestCase {
int initialEnergy;
int initialExperience;
std::vector<int> energy;
std::vector<int> experience;
int expected;
};

std::vector<TestCase> 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);
}
}

0 comments on commit d46cc2b

Please sign in to comment.