Skip to content

Commit 2c29a1b

Browse files
authored
Update 2025-maximum-number-of-ways-to-partition-an-array.js
1 parent 89d6ad2 commit 2c29a1b

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

2025-maximum-number-of-ways-to-partition-an-array.js

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,45 @@
1+
/**
2+
* @param {number[]} nums
3+
* @param {number} k
4+
* @return {number}
5+
*/
6+
const waysToPartition = function (nums, k) {
7+
const n = nums.length, pre = Array(n).fill(0), suf = Array(n).fill(0)
8+
pre[0] = nums[0], suf[n - 1] = nums[n - 1]
9+
for(let i = 1; i < n; i++) {
10+
pre[i] = pre[i - 1] + nums[i]
11+
suf[n - 1 - i] = suf[n - i] + nums[n - 1 - i]
12+
}
13+
const sum = nums.reduce((ac, e) => ac + e, 0)
14+
let res = 0
15+
for(let i = 0; i < n - 1; i++) {
16+
if(pre[i] === suf[i + 1]) res++
17+
}
18+
const cnt = new Map()
19+
const arr = Array(n).fill(0)
20+
for(let i = 0; i < n; i++) {
21+
const newSum = sum - nums[i] + k
22+
if(newSum % 2 === 0) arr[i] += (cnt.get(newSum / 2) || 0)
23+
cnt.set(pre[i], (cnt.get(pre[i]) || 0) + 1)
24+
}
25+
cnt.clear()
26+
for(let i = n - 1; i >= 0; i--) {
27+
const newSum = sum - nums[i] + k
28+
if(newSum % 2 === 0) arr[i] += (cnt.get(newSum / 2) || 0)
29+
cnt.set(suf[i], (cnt.get(suf[i]) || 0) + 1)
30+
}
31+
32+
for(let e of arr) {
33+
if(e > res) res = e
34+
}
35+
36+
return res
37+
}
38+
39+
40+
// another
41+
42+
143
/**
244
* @param {number[]} nums
345
* @param {number} k

0 commit comments

Comments
 (0)