LeetCode Solutions

1013. Partition Array Into Three Parts With Equal Sum

Time:

Space:

			

class Solution {
 public:
  bool canThreePartsEqualSum(vector<int>& A) {
    int sum = accumulate(begin(A), end(A), 0);
    int prefix = 0;
    int parts = 1;

    for (int a : A) {
      prefix += a;
      if (prefix == sum * parts / 3)
        ++parts;
    }

    return sum % 3 == 0 && parts >= 3;
  }
};
			

class Solution {
  public boolean canThreePartsEqualSum(int[] A) {
    int sum = Arrays.stream(A).sum();
    int prefix = 0;
    int parts = 1;

    for (int a : A) {
      prefix += a;
      if (prefix == sum * parts / 3)
        ++parts;
    }

    return sum % 3 == 0 && parts >= 3;
  }
}
			

class Solution:
  def canThreePartsEqualSum(self, A: List[int]) -> bool:
    summ = sum(A)
    prefix = 0
    parts = 1

    for a in A:
      prefix += a
      if prefix == summ * parts // 3:
        parts += 1

    return summ % 3 == 0 and parts >= 3