LeetCode: Partition Array Into Three Parts With Equal Sum

Question

Given an array of integers arr, return true 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 (arr[0] + arr[1] + … + arr[i] == arr[i + 1] + arr[i + 2] + … + arr[j - 1] == arr[j] + arr[j + 1] + … + arr[arr.length - 1])

Example 1:
Input: arr = [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: arr = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false

Example 3:
Input: arr = [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4

Solution#1

def can_three_parts_equal_sum(arr)
  limit = arr.sum / 3.0
  return false unless (arr.sum%3).zero?
  result = []
  seg = []
  temp = []
  sum = 0

  arr.each_with_index do |num, i|
    seg << num
    sum += num
    if sum == limit
      temp = seg.dup
      result << temp.sum
      seg.clear
      sum = 0
    end
  end
  return false if result.size < 3
  result.uniq.size == 1
end

Solution#2

def can_three_parts_equal_sum(arr)
  limit = arr.sum / 3
  return false unless (arr.sum%3).zero?

  count = 0
  sum = 0
  arr.each do |num|
    sum += num
    if sum == limit
      count += 1
      sum = 0
    end
  end
  count >= 3
end