2270. Number of Ways to Split Array
Difficulty: Medium
Topics: Array, Prefix Sum
You are given a 0-indexed integer array nums of length n.
nums contains a valid split at index i if the following are true:
- The sum of the first
i + 1elements is greater than or equal to the sum of the lastn - i - 1elements. - There is at least one element to the right of
i. That is,0 <= i < n - 1.
Return the number of valid splits in nums.
Example 1:
Input: nums = [10,4,-8,7]
Output: 2
Explanation: There are three ways of splitting nums into two non-empty parts:
- Split nums at index
0. Then, the first part is[10], and its sum is10. The second part is[4,-8,7], and its sum is3. Since10 >= 3,i = 0is a valid split. - Split nums at index
1. Then, the first part is[10,4], and its sum is14. The second part is[-8,7], and its sum is-1. Since14 >= -1,i = 1is a valid split. - Split nums at index
2. Then, the first part is[10,4,-8], and its sum is6. The second part is[7], and its sum is7. Since6 < 7,i = 2is not a valid split. - Thus, the number of valid splits in nums is
2.
- Split nums at index
Example 2:
Input: nums = [2,3,1,0]
Output: 2
Explanation: There are two valid splits in nums:
- Split nums at index
1. Then, the first part is[2,3], and its sum is5. The second part is[1,0], and its sum is1. Since5 >= 1,i = 1is a valid split. - Split nums at index
2. Then, the first part is[2,3,1], and its sum is6. The second part is[0], and its sum is0. Since6 >= 0,i = 2is a valid split.
- Split nums at index
Constraints:
2 <= nums.length <= 105-105 <= nums[i] <= 105
Hint:
- For any index
i, how can we find thesumof the first(i+1)elements from thesumof the firstielements? - If the total
sumof the array is known, how can we check if thesumof the first(i+1)elementsgreater than or equal tothe remaining elements?
Solution:
We can approach it using the following steps:
Approach:
Prefix Sum: First, we compute the cumulative sum of the array from the left, which helps in checking the sum of the firsti+1elements.
Total Sum: Compute the total sum of the array, which is useful in checking if the sum of the remaining elements is less than or equal to the sum of the firsti+1elements.
Iterate over the array: For each valid indexi(where0 <= i < n-1), we check if the sum of the firsti+1elements is greater than or equal to the sum of the lastn-i-1elements.
Efficiency: Instead of recalculating the sums repeatedly, use the prefix sum and the total sum for efficient comparisons.
Let's implement this solution in PHP: a star on GitHub or sharing the post on your favorite social networks 😍.
SOCIAL SHARE CARD GENERATOR