|
| 1 | +/** |
| 2 | + * 2025. Maximum Number of Ways to Partition an Array |
| 3 | + * https://leetcode.com/problems/maximum-number-of-ways-to-partition-an-array/ |
| 4 | + * Difficulty: Hard |
| 5 | + * |
| 6 | + * You are given a 0-indexed integer array nums of length n. The number of ways to partition |
| 7 | + * nums is the number of pivot indices that satisfy both conditions: |
| 8 | + * - 1 <= pivot < n |
| 9 | + * - nums[0] + nums[1] + ... + nums[pivot - 1] == nums[pivot] + nums[pivot + 1] + ... + nums[n - 1] |
| 10 | + * |
| 11 | + * You are also given an integer k. You can choose to change the value of one element of nums to |
| 12 | + * k, or to leave the array unchanged. |
| 13 | + * |
| 14 | + * Return the maximum possible number of ways to partition nums to satisfy both conditions after |
| 15 | + * changing at most one element. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[]} nums |
| 20 | + * @param {number} k |
| 21 | + * @return {number} |
| 22 | + */ |
| 23 | +var waysToPartition = function(nums, k) { |
| 24 | + const n = nums.length; |
| 25 | + const prefixSums = [nums[0]]; |
| 26 | + const leftDiffs = new Map(); |
| 27 | + const rightDiffs = new Map(); |
| 28 | + |
| 29 | + for (let i = 1; i < n; i++) { |
| 30 | + prefixSums[i] = prefixSums[i - 1] + nums[i]; |
| 31 | + const diff = prefixSums[i - 1]; |
| 32 | + rightDiffs.set(diff, (rightDiffs.get(diff) || 0) + 1); |
| 33 | + } |
| 34 | + |
| 35 | + const totalSum = prefixSums[n - 1]; |
| 36 | + let result = totalSum % 2 === 0 ? (rightDiffs.get(totalSum / 2) || 0) : 0; |
| 37 | + |
| 38 | + for (let i = 0; i < n; i++) { |
| 39 | + const delta = k - nums[i]; |
| 40 | + const newTotalSum = totalSum + delta; |
| 41 | + |
| 42 | + if (newTotalSum % 2 === 0) { |
| 43 | + const targetSum = newTotalSum / 2; |
| 44 | + const waysFromLeft = leftDiffs.get(targetSum) || 0; |
| 45 | + const waysFromRight = rightDiffs.get(targetSum - delta) || 0; |
| 46 | + result = Math.max(result, waysFromLeft + waysFromRight); |
| 47 | + } |
| 48 | + |
| 49 | + if (i < n - 1) { |
| 50 | + const currentDiff = prefixSums[i]; |
| 51 | + leftDiffs.set(currentDiff, (leftDiffs.get(currentDiff) || 0) + 1); |
| 52 | + rightDiffs.set(currentDiff, rightDiffs.get(currentDiff) - 1); |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return result; |
| 57 | +}; |
0 commit comments