Skip to content

Commit

Permalink
Maximum Score of a Good Subarray
Browse files Browse the repository at this point in the history
  • Loading branch information
hikjik committed Oct 22, 2023
1 parent d97daf2 commit 3f8fa8a
Show file tree
Hide file tree
Showing 4 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,7 @@ add_task(maximum-product-of-two-elements-in-an-array)
add_task(maximum-product-subarray)
add_task(maximum-profit-in-job-scheduling)
add_task(maximum-running-time-of-n-computers)
add_task(maximum-score-of-a-good-subarray)
add_task(maximum-score-words-formed-by-letters)
add_task(maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold)
add_task(maximum-subarray)
Expand Down
1 change: 1 addition & 0 deletions solutions/maximum-score-of-a-good-subarray/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
add_catch(test_maximum_score_of_a_good_subarray test.cpp)
20 changes: 20 additions & 0 deletions solutions/maximum-score-of-a-good-subarray/solution.hpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#pragma once

#include <vector>

class Solution {
public:
static int maximumScore(const std::vector<int> &nums, int k) {
const int n = nums.size();
int max_score = nums[k];
for (int l = k, r = k, min = nums[k]; l > 0 || r < n - 1;) {
if (l == 0 || r < n - 1 && nums[l - 1] < nums[r + 1]) {
min = std::min(min, nums[++r]);
} else {
min = std::min(min, nums[--l]);
}
max_score = std::max(max_score, min * (r - l + 1));
}
return max_score;
}
};
34 changes: 34 additions & 0 deletions solutions/maximum-score-of-a-good-subarray/test.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include <catch.hpp>

#include <solution.hpp>

TEST_CASE("Simple") {
struct TestCase {
std::vector<int> nums;
int k;
int expected;
};

std::vector<TestCase> test_cases{
{
.nums{5, 5, 4, 5, 4, 1, 1, 1},
.k = 0,
.expected = 20,
},
{
.nums{6569, 9667, 3148, 7698, 1622, 2194, 793, 9041, 1670, 1872},
.k = 5,
.expected = 9732,
},
{
.nums{1, 4, 3, 7, 4, 5},
.k = 3,
.expected = 15,
},
};

for (const auto &[nums, k, expected] : test_cases) {
const auto actual = Solution::maximumScore(nums, k);
REQUIRE(expected == actual);
}
}

0 comments on commit 3f8fa8a

Please sign in to comment.