From 3fbd7623d9238a24f55b4aa282233a8bbfd36941 Mon Sep 17 00:00:00 2001 From: Eatswap Date: Wed, 19 Apr 2023 18:40:52 +0800 Subject: [PATCH] add: 230419-CN --- cpp/2304/230419-CN.cpp | 53 +++++++++++++++++++++++++++++++++++++++++ cpp/2304/CMakeLists.txt | 2 +- 2 files changed, 54 insertions(+), 1 deletion(-) create mode 100644 cpp/2304/230419-CN.cpp diff --git a/cpp/2304/230419-CN.cpp b/cpp/2304/230419-CN.cpp new file mode 100644 index 0000000..2e09428 --- /dev/null +++ b/cpp/2304/230419-CN.cpp @@ -0,0 +1,53 @@ +#include +#include +#include + +/** + * 1043. Partition Array for Maximum Sum + * + * Given an integer array arr, partition the array into (contiguous) subarrays of length at most k. After partitioning, each subarray has their values changed to become the maximum value of that subarray. + * Return the largest sum of the given array after partitioning. Test cases are generated so that the answer fits in a 32-bit integer. + */ + +class Solution { +private: + int dp[512]{}; + const std::vector* ptr = nullptr; + int k = 0; + + int d(int pos) noexcept; + +public: + int maxSumAfterPartitioning(const std::vector&, int) noexcept; +}; + +int Solution::maxSumAfterPartitioning(const std::vector& arr, int k) noexcept { + this->ptr = &arr; + this->k = k; + return d(0); +} + +int Solution::d(int pos) noexcept { + if (pos >= ptr->size()) + return 0; + auto& ans = dp[pos]; + if (ans) + return ans; + for (int i = 0, m = 0; i < k; ++i) { + int c_pos = pos + i; + if (c_pos >= ptr->size()) + break; + m = std::max(m, ptr->operator[](i + pos)); + ans = std::max(ans, m * (i + 1) + d(pos + i + 1)); + } + return ans; +} + +int main() { + Solution s; + std::cout << s.maxSumAfterPartitioning( + {1,15,7,9,2,5,10}, + 3 + ); + return 0; +} \ No newline at end of file diff --git a/cpp/2304/CMakeLists.txt b/cpp/2304/CMakeLists.txt index aa1f5e7..04b7d85 100644 --- a/cpp/2304/CMakeLists.txt +++ b/cpp/2304/CMakeLists.txt @@ -4,4 +4,4 @@ PROJECT(2304) SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_EXPORT_COMPILE_COMMANDS true) -ADD_EXECUTABLE(2304 230418-CN.cpp) +ADD_EXECUTABLE(2304 230419-CN.cpp)