Partition Array Into Three Parts With Equal Sum
Description
Given an array A
of integers, return true
if and only if we can partition the array into three non-empty parts with equal sums.
Formally, we can partition the array if we can find indexes i+1 < j
with (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1])
Example 1:
Input: A = [0,2,1,-6,6,-7,9,1,2,0,1] Output: true Explanation: 0 + 2 + 1 = -6 + 6 - 7 + 9 + 1 = 2 + 0 + 1
Example 2:
Input: A = [0,2,1,-6,6,7,9,-1,2,0,1] Output: false
Example 3:
Input: A = [3,3,6,5,-2,2,5,1,-9,4] Output: true Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
Constraints:
3 <= A.length <= 50000
-10^4 <= A[i] <= 10^4
Solution(javascript)
/** 这个没看清题,题目的意思是按顺序相加的,那就简单了
* @param {number[]} A
* @return {boolean}
*/
// const canThreePartsEqualSum = function (A) {
// const map = {}
// const sum = A.reduce((acc, v) => {
// map[v] = (map[v] || 0) + 1
// return acc + v
// }, 0)
// if (!Number.isInteger(sum / 3)) {
// return false
// }
// let count = 0
// let currentSum = 0
// const target = sum / 3
// for (const num of A) {
// if (map[num] > 0) {
// map[num] -= 1
// currentSum += num
// if (currentSum === target) {
// count += 1
// currentSum = 0
// } else if (map[target - currentSum] > 0) {
// map[target - currentSum] -= 1
// currentSum = 0
// count += 1
// }
// }
// }
// return count === 3
// }
const canThreePartsEqualSum = function (A) {
const sum = A.reduce((acc, v) => acc + v, 0)
if (!Number.isInteger(sum / 3)) {
return false
}
let count = 0
let currentSum = 0
const target = sum / 3
for (const num of A) {
currentSum += num
if (currentSum === target) {
currentSum = 0
count += 1
}
}
return count === 3 && currentSum === 0
}