Skip to content

Commit a13d83f

Browse files
authored
Create maximum-number-of-ways-to-partition-an-array.py
1 parent 57f5228 commit a13d83f

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
import collections
5+
6+
7+
class Solution(object):
8+
def waysToPartition(self, nums, k):
9+
"""
10+
:type nums: List[int]
11+
:type k: int
12+
:rtype: int
13+
"""
14+
right = collections.Counter()
15+
total = sum(nums)
16+
prefix = 0
17+
for i in xrange(len(nums)-1):
18+
prefix += nums[i]
19+
right[prefix-(total-prefix)] += 1
20+
result = right[0]
21+
left = collections.Counter()
22+
prefix = 0
23+
for x in nums:
24+
result = max(result, left[k-x]+right[-(k-x)])
25+
prefix += x
26+
left[prefix-(total-prefix)] += 1
27+
right[prefix-(total-prefix)] -= 1
28+
return result

0 commit comments

Comments
 (0)