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 :
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
Approach:
C++
#include <bits/stdc++.h>using namespace std;bool canThreePartsEqualSum(vector<int> &arr){//find sum of all elements of the arrayint summ = accumulate(arr.begin(), arr.end(), 0);//variable to hold the part sumint part = 0;//variable to hold the count of//partsint count = 0;//if sum is divisible by 3if (summ % 3 == 0){//iterate for all elements of the arrayfor (int x : arr){//update part sumpart += x;//if part sum is total sum /3if (part == (summ / 3)){//update countcount++;//reset part sumpart = 0;}}}return count >= 3;}int main(){vector<int> arr = {0, 2, 1, -6, 6, -7, 9, 1, 2, 0, 1};if (canThreePartsEqualSum(arr))cout << "true";elsecout << "false";return 0;}
No comments:
Post a Comment