Considere una array A de n enteros. Determine si la array A se puede dividir en tres partes consecutivas de modo que la suma de cada parte sea igual. En caso afirmativo, imprima cualquier par de índices (i, j) tal que sum(arr[0..i]) = sum(arr[i+1..j]) = sum(arr[j+1..n-1 ]), de lo contrario imprima -1.
Ejemplos:
Input : arr[] = {1, 3, 4, 0, 4} Output : (1, 2) Sum of subarray arr[0..1] is equal to sum of subarray arr[2..3] and also to sum of subarray arr[4..4]. The sum is 4. Input : arr[] = {2, 3, 4} Output : -1 No three subarrays exist which have equal sum.
Una solución simple es primero encontrar todos los subarreglos, almacenar la suma de estos subarreglos con sus puntos inicial y final, y luego encontrar tres subarreglos continuos disjuntos con la misma suma. La complejidad temporal de esta solución será cuadrática.
un eficienteLa solución es encontrar primero la suma S de todos los elementos del arreglo. Comprueba si esta suma es divisible por 3 o no. Esto se debe a que si la suma no es divisible, la suma no se puede dividir en tres conjuntos de sumas iguales. Si hay tres subarreglos contiguos con igual suma, entonces la suma de cada subarreglo es S/3. Suponga que el par de índices requerido es (i, j) tal que sum(arr[0..i]) = sum(arr[i+1..j]) = S/3. También sum(arr[0..i]) = preSum[i] y sum(arr[i+1..j]) = preSum[j] – preSum[i]. Esto da presuSum[i] = presuSum[j] – presuSum[i] = S/3. Esto da presuSuma[j] = 2*preSuma[i]. Así, el problema se reduce a encontrar dos índices i y j tales que presuSum[i] = S/3 y presuSum[j] = 2*(S/3).
Para encontrar estos dos índices, recorra la array y almacene la suma hasta el elemento actual en una variable preSum. Comprobar si preSum es igual a S/3 y 2*(S/3).
Implementación:
C++
// CPP program to determine if array arr[] // can be split into three equal sum sets. #include <bits/stdc++.h> using namespace std; // Function to determine if array arr[] // can be split into three equal sum sets. int findSplit(int arr[], int n) { int i; // variable to store prefix sum int preSum = 0; // variables to store indices which // have prefix sum divisible by S/3. int ind1 = -1, ind2 = -1; // variable to store sum of // entire array. int S; // Find entire sum of the array. S = arr[0]; for (i = 1; i < n; i++) S += arr[i]; // Check if array can be split in // three equal sum sets or not. if (S % 3 != 0) return 0; // Variables to store sum S/3 // and 2*(S/3). int S1 = S / 3; int S2 = 2 * S1; // Loop until second last index // as S2 should not be at the last for (i = 0; i < n - 1; i++) { preSum += arr[i]; // If prefix sum is equal to S/3 // store current index. if (preSum == S1 && ind1 == -1) ind1 = i; // If prefix sum is equal to 2* (S/3) // store current index. else if (preSum == S2 && ind1 != -1) { ind2 = i; // Come out of the loop as both the // required indices are found. break; } } // If both the indices are found // then print them. if (ind1 != -1 && ind2 != -1) { cout << "(" << ind1 << ", " << ind2 << ")"; return 1; } // If indices are not found return 0. return 0; } // Driver code int main() { int arr[] = { 1, 3, 4, 0, 4 }; int n = sizeof(arr) / sizeof(arr[0]); if (findSplit(arr, n) == 0) cout << "-1"; return 0; }
C
// C program to determine if array arr[] can be split into // three equal sum sets. #include <stdio.h> // Function to determine if array arr[] can be split into // three equal sum sets. int findSplit(int arr[], int n) { int i; // variable to store prefix sum int preSum = 0; // variables to store indices which have prefix sum // divisible by S/3. int ind1 = -1, ind2 = -1; // variable to store sum of entire array. int S; // Find entire sum of the array. S = arr[0]; for (i = 1; i < n; i++) S += arr[i]; // Check if array can be split in three equal sum sets // or not. if (S % 3 != 0) return 0; // Variables to store sum S/3 and 2*(S/3). int S1 = S / 3; int S2 = 2 * S1; // Loop until second last index as S2 should not be at // the last for (i = 0; i < n - 1; i++) { preSum += arr[i]; // If prefix sum is equal to S/3 store current // index. if (preSum == S1 && ind1 == -1) ind1 = i; // If prefix sum is equal to 2* (S/3) store current // index. else if (preSum == S2 && ind1 != -1) { ind2 = i; // Come out of the loop as both the required // indices are found. break; } } // If both the indices are found then print them. if (ind1 != -1 && ind2 != -1) { printf("(%d,%d)", ind1, ind2); return 1; } // If indices are not found return 0. return 0; } // Driver code int main() { int arr[] = { 1, 3, 4, 0, 4 }; int n = sizeof(arr) / sizeof(arr[0]); if (findSplit(arr, n) == 0) printf("-1"); return 0; } // This code is contributed by Aditya Kumar (adityakumar129)
Java
// Java program to determine if array arr[] // can be split into three equal sum sets. import java.io.*; import java.util.*; public class GFG { // Function to determine if array arr[] // can be split into three equal sum sets. static int findSplit(int[] arr, int n) { int i; // variable to store prefix sum int preSum = 0; // variables to store indices which // have prefix sum divisible by S/3. int ind1 = -1, ind2 = -1; // variable to store sum of // entire array. int S; // Find entire sum of the array. S = arr[0]; for (i = 1; i < n; i++) S += arr[i]; // Check if array can be split in // three equal sum sets or not. if (S % 3 != 0) return 0; // Variables to store sum S/3 // and 2*(S/3). int S1 = S / 3; int S2 = 2 * S1; // Loop until second last index // as S2 should not be at the last for (i = 0; i < n - 1; i++) { preSum += arr[i]; // If prefix sum is equal to S/3 // store current index. if (preSum == S1 && ind1 == -1) ind1 = i; // If prefix sum is equal to 2*(S/3) // store current index. else if (preSum == S2 && ind1 != -1) { ind2 = i; // Come out of the loop as both the // required indices are found. break; } } // If both the indices are found // then print them. if (ind1 != -1 && ind2 != -1) { System.out.print("(" + ind1 + ", " + ind2 + ")"); return 1; } // If indices are not found return 0. return 0; } // Driver code public static void main(String args[]) { int[] arr = { 1, 3, 4, 0, 4 }; int n = arr.length; if (findSplit(arr, n) == 0) System.out.print("-1"); } } // This code is contributed by Aditya Kumar (adityakumar129)
Python3
# Python3 program to determine if array arr[] # can be split into three equal sum sets. # Function to determine if array arr[] # can be split into three equal sum sets. def findSplit(arr, n): # variable to store prefix sum preSum = 0 # variables to store indices which # have prefix sum divisible by S/3. ind1 = -1 ind2 = -1 # variable to store sum of # entire array. S # Find entire sum of the array. S = arr[0] for i in range(1, n): S += arr[i] # Check if array can be split in # three equal sum sets or not. if(S % 3 != 0): return 0 # Variables to store sum S/3 # and 2*(S/3). S1 = S / 3 S2 = 2 * S1 # Loop until second last index # as S2 should not be at the last for i in range(0,n-1): preSum += arr[i] # If prefix sum is equal to S/3 # store current index. if (preSum == S1 and ind1 == -1): ind1 = i # If prefix sum is equal to 2*(S/3) # store current index. elif(preSum == S2 and ind1 != -1): ind2 = i # Come out of the loop as both the # required indices are found. break # If both the indices are found # then print them. if (ind1 != -1 and ind2 != -1): print ("({}, {})".format(ind1,ind2)) return 1 # If indices are not found return 0. return 0 # Driver code arr = [ 1, 3, 4, 0, 4 ] n = len(arr) if (findSplit(arr, n) == 0) : print ("-1") # This code is contributed by Manish Shaw # (manishshaw1)
C#
// C# program to determine if array arr[] // can be split into three equal sum sets. using System; using System.Collections.Generic; class GFG { // Function to determine if array arr[] // can be split into three equal sum sets. static int findSplit(int []arr, int n) { int i; // variable to store prefix sum int preSum = 0; // variables to store indices which // have prefix sum divisible by S/3. int ind1 = -1, ind2 = -1; // variable to store sum of // entire array. int S; // Find entire sum of the array. S = arr[0]; for (i = 1; i < n; i++) S += arr[i]; // Check if array can be split in // three equal sum sets or not. if(S % 3 != 0) return 0; // Variables to store sum S/3 // and 2*(S/3). int S1 = S / 3; int S2 = 2 * S1; // Loop until second last index // as S2 should not be at the last for (i = 0; i < n-1; i++) { preSum += arr[i]; // If prefix sum is equal to S/3 // store current index. if (preSum == S1 && ind1 == -1) ind1 = i; // If prefix sum is equal to S/3 // store current index. else if(preSum == S2 && ind1 != -1) { ind2 = i; // Come out of the loop as both the // required indices are found. break; } } // If both the indices are found // then print them. if (ind1 != -1 && ind2 != -1) { Console.Write("(" + ind1 + ", " + ind2 + ")"); return 1; } // If indices are not found return 0. return 0; } // Driver code public static void Main() { int []arr = { 1, 3, 4, 0, 4 }; int n = arr.Length; if (findSplit(arr, n) == 0) Console.Write("-1"); } } // This code is contributed by Manish Shaw // (manishshaw1)
PHP
<?php // PHP program to determine if array arr[] // can be split into three equal sum sets. // Function to determine if array arr[] // can be split into three equal sum sets. function findSplit( $arr, $n) { $i; // variable to store prefix sum $preSum = 0; // variables to store indices which // have prefix sum divisible by S/3. $ind1 = -1; $ind2 = -1; // variable to store sum of // entire array. $S; // Find entire sum of the array. $S = $arr[0]; for ($i = 1; $i < $n; $i++) $S += $arr[$i]; // Check if array can be split in // three equal sum sets or not. if($S % 3 != 0) return 0; // Variables to store sum S/3 // and 2*(S/3). $S1 = $S / 3; $S2 = 2 * $S1; // Loop until second last index // as S2 should not be at the last for ($i = 0; $i < $n-1; $i++) { $preSum += $arr[$i]; // If prefix sum is equal to S/3 // store current index. if ($preSum == $S1 and $ind1 == -1) $ind1 = $i; // If prefix sum is equal to S/3 // store current index. else if($preSum == $S2 and $ind1 != -1) { $ind2 = $i; // Come out of the loop as both the // required indices are found. break; } } // If both the indices are found // then print them. if ($ind1 != -1 and $ind2 != -1) { echo "(" , $ind1 , ", " , $ind2 , ")"; return 1; } // If indices are not found return 0. return 0; } // Driver code $arr = array( 1, 3, 4, 0, 4 ); $n = count($arr); if (findSplit($arr, $n) == 0) echo "-1"; // This code is contributed by anuj_67. ?>
Javascript
<script> // Javascript program to determine if array arr[] // can be split into three equal sum sets. // Function to determine if array arr[] // can be split into three equal sum sets. function findSplit(arr, n) { var i; // variable to store prefix sum var preSum = 0; // variables to store indices which // have prefix sum divisible by S/3. var ind1 = -1, ind2 = -1; // variable to store sum of // entire array. var S; // Find entire sum of the array. S = arr[0]; for (i = 1; i < n; i++) S += arr[i]; // Check if array can be split in // three equal sum sets or not. if(S % 3 != 0) return 0; // Variables to store sum S/3 // and 2*(S/3). var S1 = S / 3; var S2 = 2 * S1; // Loop until second last index // as S2 should not be at the last for (i = 0; i < n-1; i++) { preSum += arr[i]; // If prefix sum is equal to S/3 // store current index. if (preSum == S1 && ind1 == -1) ind1 = i; // If prefix sum is equal to 2* (S/3) // store current index. else if(preSum == S2 && ind1 != -1) { ind2 = i; // Come out of the loop as both the // required indices are found. break; } } // If both the indices are found // then print them. if (ind1 != -1 && ind2 != -1) { document.write( "(" + ind1 + ", " + ind2 + ")"); return 1; } // If indices are not found return 0. return 0; } // Driver code var arr = [ 1, 3, 4, 0, 4 ]; var n = arr.length; if (findSplit(arr, n) == 0) document.write( "-1"); // This code is contributed by rrrtnx. </script>
(1, 2)
Complejidad temporal: O(n)
Espacio auxiliar: O(1)