Skip to content

Commit 57f5228

Browse files
authored
Create maximum-number-of-ways-to-partition-an-array.cpp
1 parent 5a96338 commit 57f5228

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
class Solution {
5+
public:
6+
int waysToPartition(vector<int>& nums, int k) {
7+
const int64_t total = accumulate(begin(nums), end(nums), 0LL);
8+
unordered_map<int64_t, int> right;
9+
for (int64_t i = 0, prefix = 0; i < size(nums) - 1; ++i) {
10+
prefix += nums[i];
11+
++right[prefix - (total - prefix)];
12+
}
13+
int64_t result = right[0];
14+
unordered_map<int64_t, int> left;
15+
int64_t prefix = 0;
16+
for (const auto& x : nums) {
17+
result = max(result, static_cast<int64_t>(left[k - x]) + right[-(k - x)]);
18+
prefix += x;
19+
--right[prefix - (total - prefix)];
20+
++left[prefix - (total - prefix)];
21+
}
22+
return result;
23+
}
24+
};

0 commit comments

Comments
 (0)