Skip to content

Commit 89d6ad2

Browse files
authored
Create 2025-maximum-number-of-ways-to-partition-an-array.js
1 parent 05a7864 commit 89d6ad2

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
const waysToPartition = function (nums, k) {
7+
const n = nums.length
8+
const pref = Array(n).fill(0),
9+
suff = Array(n).fill(0)
10+
pref[0] = nums[0]
11+
suff[n - 1] = nums[n - 1]
12+
for (let i = 1; i < n; ++i) {
13+
pref[i] = pref[i - 1] + nums[i]
14+
suff[n - 1 - i] = suff[n - i] + nums[n - 1 - i]
15+
}
16+
let ans = 0
17+
const left = {},
18+
right = {}
19+
20+
for (let i = 0; i < n - 1; ++i) {
21+
const delta = pref[i] - suff[i + 1]
22+
if (right[delta] == null) right[delta] = 0
23+
right[delta]++
24+
}
25+
26+
if (right[0]) ans = right[0]
27+
for (let i = 0; i < n; ++i) {
28+
//find the number of pivot indexes when nums[i] is changed to k
29+
let curr = 0,
30+
diff = k - nums[i]
31+
if (left[diff]) curr += left[diff]
32+
if (right[-diff]) curr += right[-diff]
33+
34+
//update answer
35+
ans = Math.max(ans, curr)
36+
37+
//transfer the current element from right to left
38+
if (i < n - 1) {
39+
let dd = pref[i] - suff[i + 1]
40+
if(left[dd] == null) left[dd] = 0
41+
if(right[dd] == null) right[dd] = 0
42+
left[dd]++
43+
right[dd]--
44+
if (right[dd] == 0) delete right[dd]
45+
}
46+
}
47+
return ans
48+
}

0 commit comments

Comments
 (0)