aboutsummaryrefslogtreecommitdiff
path: root/other/partition_array_max_sum.cpp
diff options
context:
space:
mode:
authorJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
committerJack Sangdahl <[email protected]>2025-03-10 00:36:13 -0600
commit7c60dee83b436e8e8a667bf9f191beced8de4fc3 (patch)
treeeb7a24ee2067f92245c57bb118e85a1baf15df50 /other/partition_array_max_sum.cpp
parent5d7cdc215e4ba1ec4cbb24c084cccb5e5e641468 (diff)
downloadleetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.tar.gz
leetcode-7c60dee83b436e8e8a667bf9f191beced8de4fc3.zip
chore: move cpp and rust code to directory
Diffstat (limited to 'other/partition_array_max_sum.cpp')
-rw-r--r--other/partition_array_max_sum.cpp36
1 files changed, 36 insertions, 0 deletions
diff --git a/other/partition_array_max_sum.cpp b/other/partition_array_max_sum.cpp
new file mode 100644
index 0000000..98efe07
--- /dev/null
+++ b/other/partition_array_max_sum.cpp
@@ -0,0 +1,36 @@
+// 1043. Partition Array for Maximum Sum
+#include "leetcode.h"
+
+/*
+ * given an integeer 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
+ * answer fits in a 32-bit integer
+ */
+
+class Solution {
+public:
+ int maxSumAfterPartitioning(vector<int> &arr, int k) {
+ int n = arr.size();
+ vector<int> dp(n + 1);
+ for (int i = 1; i <= n; ++i) {
+ int curr = 0, best = 0;
+ for (int j = 1; j <= k && i - j >= 0; ++j) {
+ curr = max(curr, arr[i - j]);
+ best = max(best, dp[i - j] + curr * j);
+ }
+ dp[i] = best;
+ }
+ return dp[n];
+ }
+};
+
+int main() {
+ Solution obj;
+ vector<int> a1 = {1, 15, 7, 9, 2, 5, 10},
+ a2 = {1, 4, 1, 5, 7, 3, 6, 1, 9, 9, 3}, a3 = {1};
+ printf("%d\n", obj.maxSumAfterPartitioning(a1, 3)); // expect: 84
+ printf("%d\n", obj.maxSumAfterPartitioning(a2, 4)); // expect: 83
+ printf("%d\n", obj.maxSumAfterPartitioning(a3, 1)); // expect: 1
+}