03. Find Maximum Equal sum of Three Stacks
The problem can be found at the following link: Question Link
My Approach
To find the maximum equal sum among three given arrays (S1
, S2
, and S3
), I have used the following approach:
Initialize an unordered map
mp
to store the cumulative sums of the elements encountered so far and their frequencies.Traverse the first array (
S1
) in reverse order. At each index, calculate the cumulative sums
by adding the current element to the previous sum. Increment the frequency ofs
in the mapmp
.Similarly, traverse the second array (
S2
) in reverse order. At each index, calculate the cumulative sums
by adding the current element to the previous sum. Check ifs
exists in the mapmp
. If it does, increment its frequency in the map.Repeat the same process for the third array (
S3
).Iterate through the map
mp
and find the maximum sum (out
) for which the frequency is equal to 3.Finally, return the value of
out
.
Time and Auxiliary Space Complexity
Time Complexity:
O(N1 + N2 + N3)
, whereN1
,N2
, andN3
are the sizes of the arraysS1
,S2
, andS3
, respectively. We traverse each array once in reverse order, perform constant-time operations, and iterate through the mapmp
to find the maximum sum.Auxiliary Space Complexity: The auxiliary space complexity is
O(N1 + N2 + N3)
as we use the unordered mapmp
to store the cumulative sums and their frequencies.
Code (C++)
Contribution and Support
For discussions, questions, or doubts related to this solution, please visit our discussion section. We welcome your input and aim to foster a collaborative learning environment.
If you find this solution helpful, consider supporting us by giving a ⭐ star
to the getlost01/gfg-potd repository.
Last updated