Given an array A of integers, return true if and only 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 (A[0] + A[1] + ... + A[i] == A[i+1] + A[i+2] + ... + A[j-1] == A[j] + A[j-1] + ... + A[A.length - 1])
Example 1:
Input: A = [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: A = [0,2,1,-6,6,7,9,-1,2,0,1]
Output: false
Example 3:
Input: A = [3,3,6,5,-2,2,5,1,-9,4]
Output: true
Explanation: 3 + 3 = 6 = 5 - 2 + 2 + 5 + 1 - 9 + 4
Constraints:
3 <= A.length <= 50000
-10^4 <= A[i] <= 10^4
Solution:
using System;
using System.Collections.Generic;
using System.Text;
namespace LeetCode.AskGif.Easy.Array
{
public class CanThreePartsEqualSumSoln
{
public bool CanThreePartsEqualSum(int[] A)
{
var sum = 0;
for (int i = 0; i < A.Length; i++)
{
sum += A[i];
}
if(sum%3 != 0)
{
return false;
}
int parts = sum / 3;
int partsCount = 0;
int temp = 0;
for (int i = 0; i < A.Length; i++)
{
temp += A[i];
if(temp == parts)
{
temp = 0;
partsCount++;
}
}
return temp == 0 && partsCount >= 3;
}
}
}
Time Complexity: O(n)
Space Complexity: O(1)
Unit Tests:
using LeetCode.AskGif.Easy.Array;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace CodingUnitTest.Easy.Array
{
[TestClass]
public class CanThreePartsEqualSumSolnTests
{
[TestMethod]
public void CanThreePartsEqualSumSoln_First()
{
var arr = new int[] { 0, 2, 1, -6, 6, -7, 9, 1, 2, 0, 1 };
var expected = true;
var res = new CanThreePartsEqualSumSoln().CanThreePartsEqualSum(arr);
Assert.AreEqual(expected, res);
}
[TestMethod]
public void CanThreePartsEqualSumSoln_Second()
{
var arr = new int[] { 0, 2, 1, -6, 6, 7, 9, -1, 2, 0, 1 };
var expected = false;
var res = new CanThreePartsEqualSumSoln().CanThreePartsEqualSum(arr);
Assert.AreEqual(expected, res);
}
[TestMethod]
public void CanThreePartsEqualSumSoln_Third()
{
var arr = new int[] { 3, 3, 6, 5, -2, 2, 5, 1, -9, 4 };
var expected = true;
var res = new CanThreePartsEqualSumSoln().CanThreePartsEqualSum(arr);
Assert.AreEqual(expected, res);
}
[TestMethod]
public void CanThreePartsEqualSumSoln_Fourth()
{
var arr = new int[] { 1, -1, 1, -1 };
var expected = false;
var res = new CanThreePartsEqualSumSoln().CanThreePartsEqualSum(arr);
Assert.AreEqual(expected, res);
}
[TestMethod]
public void CanThreePartsEqualSumSoln_Fifth()
{
var arr = new int[] { 10, -10, 10, -10, 10, -10, 10, -10 };
var expected = true;
var res = new CanThreePartsEqualSumSoln().CanThreePartsEqualSum(arr);
Assert.AreEqual(expected, res);
}
}
}



