Skip to content

Instantly share code, notes, and snippets.

@lbvf50mobile
Last active January 3, 2025 22:21
Show Gist options
  • Save lbvf50mobile/705cf6c829dc7a8ff75bf3b887042f16 to your computer and use it in GitHub Desktop.
Save lbvf50mobile/705cf6c829dc7a8ff75bf3b887042f16 to your computer and use it in GitHub Desktop.
Leetcode: 2270. Number of Ways to Split Array
// Leetcode: 2270. Number of Ways to Split Array
// https://leetcode.com/problems/number-of-ways-to-split-array/description/?envType=daily-question&envId=2025-01-03
// = = = = = = = = = = = = = =
// Accepted.
// Thanks God, Jesus Christ!
// = = = = = = = = = = = = = =
// Runtime: 1 ms Beats 65.00%
// Memory: 11.59 MB Beats 22.50%
package main
import (
// "fmt"
)
func waysToSplitArray(nums []int) int {
ps := make([]int, len(nums)) // Prefix sum.
ans := 0
// Fill preifx sum.
ps[0] = nums[0]
for i := 1; i < len(nums); i += 1 {
ps[i] = ps[i-1] + nums[i]
}
// Count valid splits
for i := 0; i < len(nums)-1; i += 1 {
left, right := getSums(i, ps)
if left >= right {
ans += 1
}
}
return ans
}
func getSums(i int, ps []int) (int, int) {
n := len(ps)
total := ps[n-1]
left, right := ps[i], total-ps[i]
return left, right
}
// Leetcode: 2270. Number of Ways to Split Array
// https://leetcode.com/problems/number-of-ways-to-split-array/description/?envType=daily-question&envId=2025-01-03
// = = = = = = = = = = = = = =
// Accepted.
// Thanks God, Jesus Christ!
// = = = = = = = = = = = = = =
// Runtime: 2 ms Beats 56.76%
// Memory: 11.92 MB Beats 21.62%
// https://gist.github.com/lbvf50mobile/705cf6c829dc7a8ff75bf3b887042f16
package main
import (
// "fmt"
)
func waysToSplitArray(nums []int) int {
total := 0
ans := 0
n := len(nums)
for _, v := range nums {
total += v
}
right, left := 0, 0
for i := n - 1; i >= 1; i -= 1 {
right += nums[i]
left = total - right
if left >= right {
ans += 1
}
}
return ans
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment