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])
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
Comments