# leetcode 548 求大佬指点一二啊

1. Split Array with Equal Sum

Given an array with n integers, you need to find if there are triplets (i, j, k) which satisfies following conditions:

1. 0 < i, i + 1 < j, j + 1 < k < n - 1
2. Sum of subarrays (0, i - 1), (i + 1, j - 1), (j + 1, k - 1) and (k + 1, n - 1) should be equal.

where we define that subarray (L, R) represents a slice of the original array starting from the element indexed L to the element indexed R.

Example:

``````Input: [1,2,1,2,1,2,1]
Output: True
Explanation:
i = 1, j = 3, k = 5.
sum(0, i - 1) = sum(0, 0) = 1
sum(i + 1, j - 1) = sum(2, 2) = 1
sum(j + 1, k - 1) = sum(4, 4) = 1
sum(k + 1, n - 1) = sum(6, 6) = 1
``````

Note:

1. 1 <= n <= 2000.
2. Elements in the given array will be in range [-1,000,000, 1,000,000].

I only passed 118/120. failed in this
Input:
[1,2,1,3,0,0,2,2,1,3,3]
Output:
false
Expected:
true

``````/**
* @param {number[]} nums
* @return {boolean}
*/
var splitArray = function(nums) {
if (nums.length < 7) return false;
let result = false;
const sums = Array(nums.length).fill(0);
sums[0] = nums[0];
for (let i = 1; i < nums.length; i++) sums[i] = sums[i-1] + nums[i];

for (let i = 2; i < nums.length; i++) {
result = result || dfs(i, sums[i-2], 2);
}

return result;

function dfs (start, target, count) {
if (count < 0) return false;
if (start + count*2 + 1 - 1 >= nums.length) return false;
if (count === 0) {
//console.log(start)
//console.log(sums[nums.length - 1] - sums[start-1])
if (sums[nums.length - 1] - sums[start-1] === target) return true;
else return false;
}

for (let i = start; i + count * 2 + 1 - 1 < nums.length; i++) {
const sum = sums[i] - sums[start-1];
if (sum === target) {
return dfs(i + 2, target, count-1);
}
}

return false;
}
};
``````

#### Using Cumulative Sum and HashSet

Algorithm

Look at the animation below for a visual representation of the process:

``````public class Solution {
public boolean splitArray(int[] nums) {
if (nums.length < 7)
return false;
int[] sum = new int[nums.length];
sum[0] = nums[0];
for (int i = 1; i < nums.length; i++) {
sum[i] = sum[i - 1] + nums[i];
}
for (int j = 3; j < nums.length - 3; j++) {
HashSet < Integer > set = new HashSet < > ();
for (int i = 1; i < j - 1; i++) {
if (sum[i - 1] == sum[j - 1] - sum[i])
}
for (int k = j + 2; k < nums.length - 1; k++) {
if (sum[nums.length - 1] - sum[k] == sum[k - 1] - sum[j] && set.contains(sum[k - 1] - sum[j]))
return true;
}
}
return false;
}
}
``````

Complexity Analysis

• Time complexity : O(n^2). One outer loop and two inner loops are used.
• Space complexity : O(n). HashSet size can go up to n.