The Wayback Machine - https://web.archive.org/web/20240927175914/https://www.geeksforgeeks.org/find-maximum-sum-possible-equal-sum-three-stacks/
Open In App

Find maximum equal sum of every three stacks

Last Updated : 27 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Show Topics
Solve Problem
Medium
48.71%
45.1K

Given three stacks of the positive numbers, the task is to find the possible equal maximum sum of the stacks with the removal of top elements allowed. Stacks are represented as an array, and the first index of the array represent the top element of the stack.

Examples: 

Input : stack1[] = { 3, 10}
stack2[] = { 4, 5 }
stack3[] = { 2, 1 }
Output : 0
Sum can only be equal after removing all elements
from all stacks.

find-maximum-sum-possible-equal-sum-of-three-stacks

Method 1:

The idea is to compare the sum of each stack, if they are not same, remove the top element of the stack having the maximum sum.

Algorithm for solving this problem: 

  1. Find the sum of all elements of in individual stacks.
  2. If the sum of all three stacks is the same, then this is the maximum sum.
  3. Else remove the top element of the stack having the maximum sum among three of stacks. Repeat step 1 and step 2.

The approach works because elements are positive. To make sum equal, we must remove some element from stack having more sum, and we can only remove from the top.

Below is the implementation of this approach: 

C++
// C++ program to calculate maximum sum with equal
// stack sum.
#include <bits/stdc++.h>
using namespace std;

// Returns maximum possible equal sum of three stacks
// with removal of top elements allowed
int maxSum(int stack1[], int stack2[], int stack3[], int n1,
           int n2, int n3)
{
    int sum1 = 0, sum2 = 0, sum3 = 0;

    // Finding the initial sum of stack1.
    for (int i = 0; i < n1; i++)
        sum1 += stack1[i];

    // Finding the initial sum of stack2.
    for (int i = 0; i < n2; i++)
        sum2 += stack2[i];

    // Finding the initial sum of stack3.
    for (int i = 0; i < n3; i++)
        sum3 += stack3[i];

    // As given in question, first element is top
    // of stack..
    int top1 = 0, top2 = 0, top3 = 0;
    while (1) {
        // If any stack is empty
        if (top1 == n1 || top2 == n2 || top3 == n3)
            return 0;

        // If sum of all three stack are equal.
        if (sum1 == sum2 && sum2 == sum3)
            return sum1;

        // Finding the stack with maximum sum and
        // removing its top element.
        if (sum1 >= sum2 && sum1 >= sum3)
            sum1 -= stack1[top1++];
        else if (sum2 >= sum1 && sum2 >= sum3)
            sum2 -= stack2[top2++];
        else if (sum3 >= sum2 && sum3 >= sum1)
            sum3 -= stack3[top3++];
    }
}

// Driven Program
int main()
{
    int stack1[] = { 3, 2, 1, 1, 1 };
    int stack2[] = { 4, 3, 2 };
    int stack3[] = { 1, 1, 4, 1 };

    int n1 = sizeof(stack1) / sizeof(stack1[0]);
    int n2 = sizeof(stack2) / sizeof(stack2[0]);
    int n3 = sizeof(stack3) / sizeof(stack3[0]);

    cout << maxSum(stack1, stack2, stack3, n1, n2, n3)
         << endl;
    return 0;
}
Java
// JAVA Code for Find maximum sum possible
// equal sum of three stacks
class GFG {

    // Returns maximum possible equal sum of three
    // stacks with removal of top elements allowed
    public static int maxSum(int stack1[], int stack2[],
                             int stack3[], int n1, int n2,
                             int n3)
    {
        int sum1 = 0, sum2 = 0, sum3 = 0;

        // Finding the initial sum of stack1.
        for (int i = 0; i < n1; i++)
            sum1 += stack1[i];

        // Finding the initial sum of stack2.
        for (int i = 0; i < n2; i++)
            sum2 += stack2[i];

        // Finding the initial sum of stack3.
        for (int i = 0; i < n3; i++)
            sum3 += stack3[i];

        // As given in question, first element is top
        // of stack..
        int top1 = 0, top2 = 0, top3 = 0;
        int ans = 0;
        while (true) {
            // If any stack is empty
            if (top1 == n1 || top2 == n2 || top3 == n3)
                return 0;

            // If sum of all three stack are equal.
            if (sum1 == sum2 && sum2 == sum3)
                return sum1;

            // Finding the stack with maximum sum and
            // removing its top element.
            if (sum1 >= sum2 && sum1 >= sum3)
                sum1 -= stack1[top1++];
            else if (sum2 >= sum1 && sum2 >= sum3)
                sum2 -= stack2[top2++];
            else if (sum3 >= sum2 && sum3 >= sum1)
                sum3 -= stack3[top3++];
        }
    }

    /* Driver program to test above function */
    public static void main(String[] args)
    {
        int stack1[] = { 3, 2, 1, 1, 1 };
        int stack2[] = { 4, 3, 2 };
        int stack3[] = { 1, 1, 4, 1 };

        int n1 = stack1.length;
        int n2 = stack2.length;
        int n3 = stack3.length;

        System.out.println(
            maxSum(stack1, stack2, stack3, n1, n2, n3));
    }
}
// This code is contributed by Arnav Kr. Mandal.
Python
# Python program to calculate maximum sum with equal
# stack sum.
# Returns maximum possible equal sum of three stacks
# with removal of top elements allowed


def maxSum(stack1, stack2, stack3, n1, n2, n3):
  # Finding the initial sum of all the stacks
    sum1, sum2, sum3 = sum(stack1), sum(stack2), sum(stack3)

  # As given in question, first element is top
  # of stack..
    top1, top2, top3 = 0, 0, 0
    while (1):
      # If any stack is empty
        if (top1 == n1 or top2 == n2 or top3 == n3):
            return 0

      # If sum of all three stack are equal.
        if (sum1 == sum2 and sum2 == sum3):
            return sum1

      # Finding the stack with maximum sum and
      # removing its top element.
        if (sum1 >= sum2 and sum1 >= sum3):
            sum1 -= stack1[top1]
            top1 = top1+1
        elif (sum2 >= sum1 and sum2 >= sum3):
            sum2 -= stack2[top2]
            top2 = top2+1
        elif (sum3 >= sum2 and sum3 >= sum1):
            sum3 -= stack3[top3]
            top3 = top3+1


# Driven Program
stack1 = [3, 2, 1, 1, 1]
stack2 = [4, 3, 2]
stack3 = [1, 1, 4, 1]

n1 = len(stack1)
n2 = len(stack2)
n3 = len(stack3)

print(maxSum(stack1, stack2, stack3, n1, n2, n3))

# This code is contributed by Afzal Ansari
C#
// C# Code for Find maximum sum with
// equal sum of three stacks
using System;

class GFG {

    // Returns maximum possible equal
    // sum of three stacks with removal
    // of top elements allowed
    public static int maxSum(int[] stack1, int[] stack2,
                             int[] stack3, int n1, int n2,
                             int n3)
    {

        int sum1 = 0, sum2 = 0, sum3 = 0;

        // Finding the initial sum of
        // stack1.
        for (int i = 0; i < n1; i++)
            sum1 += stack1[i];

        // Finding the initial sum of
        // stack2.
        for (int i = 0; i < n2; i++)
            sum2 += stack2[i];

        // Finding the initial sum of
        // stack3.
        for (int i = 0; i < n3; i++)
            sum3 += stack3[i];

        // As given in question, first
        // element is top of stack..
        int top1 = 0, top2 = 0, top3 = 0;

        while (true) {

            // If any stack is empty
            if (top1 == n1 || top2 == n2 || top3 == n3)
                return 0;

            // If sum of all three stack
            // are equal.
            if (sum1 == sum2 && sum2 == sum3)
                return sum1;

            // Finding the stack with maximum
            // sum and removing its top element.
            if (sum1 >= sum2 && sum1 >= sum3)
                sum1 -= stack1[top1++];
            else if (sum2 >= sum1 && sum2 >= sum3)
                sum2 -= stack2[top2++];
            else if (sum3 >= sum2 && sum3 >= sum1)
                sum3 -= stack3[top3++];
        }
    }

    /* Driver program to test above function */
    public static void Main()
    {
        int[] stack1 = { 3, 2, 1, 1, 1 };
        int[] stack2 = { 4, 3, 2 };
        int[] stack3 = { 1, 1, 4, 1 };

        int n1 = stack1.Length;
        int n2 = stack2.Length;
        int n3 = stack3.Length;

        Console.Write(
            maxSum(stack1, stack2, stack3, n1, n2, n3));
    }
}

// This code is contributed by nitin mittal.
JavaScript
<script>

// JavaScript program to calculate maximum
// sum with equal stack sum. 

// Returns maximum possible equal sum of three 
// stacks with removal of top elements allowed
function maxSum(stack1, stack2,
                stack3, n1, n2, n3)
{
    let sum1 = 0, sum2 = 0, sum3 = 0;
    
    // Finding the initial sum of stack1.
    for(let i = 0; i < n1; i++)
        sum1 += stack1[i];
    
    // Finding the initial sum of stack2.
    for(let i = 0; i < n2; i++)
        sum2 += stack2[i];
    
    // Finding the initial sum of stack3.
    for(let i = 0; i < n3; i++)
        sum3 += stack3[i];
    
    // As given in question, first element
    // is top of stack.
    let top1 = 0, top2 = 0, top3 = 0;
    let ans = 0;
    
    while (true)
    {
        
        // If any stack is empty
        if (top1 == n1 || top2 == n2 || 
            top3 == n3)
            return 0;
            
        // If sum of all three stack are equal.
        if (sum1 == sum2 && sum2 == sum3)
            return sum1;
       
        // Finding the stack with maximum sum and 
        // removing its top element.
        if (sum1 >= sum2 && sum1 >= sum3)
            sum1 -= stack1[top1++];
        else if (sum2 >= sum1 && sum2 >= sum3)
            sum2 -= stack2[top2++];
        else if (sum3 >= sum2 && sum3 >= sum1)
            sum3 -= stack3[top3++];
    }
}

// Driver Code
let stack1 = [ 3, 2, 1, 1, 1 ];
let stack2 = [ 4, 3, 2 ];
let stack3 = [ 1, 1, 4, 1 ];

let n1 = stack1.length;
let n2 = stack2.length;
let n3 = stack3.length;

document.write(maxSum(stack1, stack2, 
                      stack3, n1, n2, n3));
                      
// This code is contributed by souravghosh0416

</script>
PHP
<?php
// PHP program to calculate maximum 
// sum with equal stack sum.

// Returns maximum possible
// equal sum of three stacks
// with removal of top elements
// allowed
function maxSum($stack1, $stack2, $stack3, 
                            $n1, $n2, $n3)
{
    $sum1 = 0; $sum2 = 0; $sum3 = 0;
    
    // Finding the initial sum of stack1.
    for ($i = 0; $i < $n1; $i++)
        $sum1 += $stack1[$i];
    
    // Finding the initial sum of stack2.
    for ($i = 0; $i < $n2; $i++)
        $sum2 += $stack2[$i];
    
    // Finding the initial sum of stack3.
    for ($i = 0; $i < $n3; $i++)
        $sum3 += $stack3[$i];
    
    // As given in question, 
    // first element is top
    // of stack..
    $top1 =0;
    $top2 = 0; 
    $top3 = 0;
    $ans = 0;
    while (1)
    {
        
        // If any stack is empty
        if ($top1 == $n1 || $top2 == $n2 ||
                              $top3 == $n3)
            return 0;
    
        // If sum of all three stack are equal.
        if ($sum1 == $sum2 && $sum2 == $sum3)
            return $sum1;
        
        // Finding the stack with
        // maximum sum and 
        // removing its top element.
        if ($sum1 >= $sum2 && $sum1 >= $sum3)
                $sum1 -= $stack1[$top1++];
                
        else if ($sum2 >= $sum1 && $sum2 >=$sum3)
                $sum2 -= $stack2[$top2++];
                
        else if ($sum3 >= $sum2 && $sum3 >= $sum1)
                $sum3 -= $stack3[$top3++];
    }
}

// Driver Code
$stack1 = array(3, 2, 1, 1, 1);
$stack2 = array(4, 3, 2);
$stack3 = array(1, 1, 4, 1);

$n1 = sizeof($stack1);
$n2 = sizeof($stack2);
$n3 = sizeof($stack3);
echo maxSum($stack1, $stack2, 
            $stack3, $n1, 
            $n2, $n3) ;
            
// This code is contributed by nitin mittal
?>

Output
5

Time Complexity : O(n1 + n2 + n3) where n1, n2 and n3 are sizes of three stacks.
Auxiliary space: O(1) because using constant space for variables

Method 2: Using suffix sum and unordered_set

The question can be reinterpreted as we need to find the maximum equal suffix sum of the three array.

As we remove element from the top of stack the remaining sum is the suffix sum up to current element. So, if we put all the suffix sums of stack1 and stack2 in an unordered set and traverse the suffix sum array of stack3, and if we find a suffix sum which is present in all three then it is our ans.

  • Calculate suffix sum of stack1 and stack2 and insert each element in unorderd_set1 and unordered_set2 respectively.
  • Calculate suffix sum of stack 3 and store in vector named as suffix.
  • Traverse the suffix vector from i = 0 to i = prefix.size() – 1
  • Find an index where the suffix sums of all the three stacks are equal
  • If not found return 0
C++
// C++ program to calculate maximum sum with equal
// stack sum.
#include <bits/stdc++.h>
using namespace std;

// Returns maximum possible equal sum of three stacks
// with removal of top elements allowed
int maxEqualSum(int N1, int N2, int N3, vector<int>& S1,
                vector<int>& S2, vector<int>& S3)
{
    vector<int> suffix(S3.size() + 1, 0);

    int sum1 = 0;
    // unordered_set st1 will contain all element of suffix
    // sum of stack1
    unordered_set<int> st1;

    // calculating suffix sum of stack1 and inserting it
    // into unordered_set st1
    for (int i = S1.size() - 1; i >= 0; i--) {
        sum1 = sum1 + S1[i];
        st1.insert(sum1);
    }

    int sum2 = 0;
    // unordered_set st1 will contain all element of suffix
    // sum of stack1
    unordered_set<int> st2;

    // calculating suffix sum of stack1 and inserting it
    // into unordered_set st1
    for (int i = S2.size() - 1; i >= 0; i--) {
        sum2 = sum2 + S2[i];
        st2.insert(sum2);
    }

    // calculating suffix sum of stack3 and storing in
    // suffix vector
    for (int i = S3.size() - 1; i >= 0; i--) {
        suffix[i] = suffix[i + 1] + S3[i];
    }

    // find the maximum suffix sum which is present in all
    // three stacks
    for (int i = 0; i < suffix.size(); i++) {
        if (st1.find(suffix[i]) != st1.end()
            && st2.find(suffix[i]) != st2.end()) {
            return suffix[i];
        }
    }
    return 0;
}

// Driven Program
int main()
{
    vector<int> stack1 = { 3, 2, 1, 1, 1 };
    vector<int> stack2 = { 4, 3, 2 };
    vector<int> stack3 = { 1, 1, 4, 1 };

    cout << maxEqualSum(stack1.size(), stack2.size(),
                        stack3.size(), stack1, stack2,
                        stack3)
         << endl;
    return 0;
}
Java
import java.io.*;
import java.util.HashSet;

public class GFG {
    // Function to calculate the maximum possible equal sum
    // of three stacks with removal of top elements allowed
    public static int maxEqualSum(int N1, int N2, int N3,
                                  int[] S1, int[] S2,
                                  int[] S3)
    {
        int[] suffix = new int[N3 + 1];
        int sum1 = 0;
        HashSet<Integer> st1 = new HashSet<>();

        // Calculating suffix sum of stack1 and inserting it
        // into Set st1
        for (int i = N1 - 1; i >= 0; i--) {
            sum1 += S1[i];
            st1.add(sum1);
        }

        int sum2 = 0;
        HashSet<Integer> st2 = new HashSet<>();

        // Calculating suffix sum of stack2 and inserting it
        // into Set st2
        for (int i = N2 - 1; i >= 0; i--) {
            sum2 += S2[i];
            st2.add(sum2);
        }

        // Calculating suffix sum of stack3 and storing it
        // in the suffix array
        for (int i = N3 - 1; i >= 0; i--) {
            suffix[i] = suffix[i + 1] + S3[i];
        }

        // Finding the maximum suffix sum which is present
        // in all three stacks
        for (int i = 0; i < suffix.length; i++) {
            if (st1.contains(suffix[i])
                && st2.contains(suffix[i])) {
                return suffix[i];
            }
        }

        return 0; // If no equal sum is found
    }

    // Driven Program
    public static void main(String[] args)
    {
        int[] stack1 = { 3, 2, 1, 1, 1 };
        int[] stack2 = { 4, 3, 2 };
        int[] stack3 = { 1, 1, 4, 1 };

        System.out.println(maxEqualSum(
            stack1.length, stack2.length, stack3.length,
            stack1, stack2, stack3));
    }
}
Python
# Function to calculate the maximum possible equal sum of three stacks
# with removal of top elements allowed


def maxEqualSum(N1, N2, N3, S1, S2, S3):
    suffix = [0] * (N3 + 1)
    sum1 = 0
    st1 = set()

    # Calculating suffix sum of stack1 and inserting it into Set st1
    for i in range(N1 - 1, -1, -1):
        sum1 += S1[i]
        st1.add(sum1)

    sum2 = 0
    st2 = set()

    # Calculating suffix sum of stack2 and inserting it into Set st2
    for i in range(N2 - 1, -1, -1):
        sum2 += S2[i]
        st2.add(sum2)

    # Calculating suffix sum of stack3 and storing it in the suffix array
    for i in range(N3 - 1, -1, -1):
        suffix[i] = suffix[i + 1] + S3[i]

    # Finding the maximum suffix sum which is present in all three stacks
    for i in range(len(suffix)):
        if suffix[i] in st1 and suffix[i] in st2:
            return suffix[i]

    return 0  # If no equal sum is found


# Driven Program
stack1 = [3, 2, 1, 1, 1]
stack2 = [4, 3, 2]
stack3 = [1, 1, 4, 1]

print(maxEqualSum(len(stack1), len(stack2), len(stack3), stack1, stack2, stack3))
# THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)
C#
using System;
using System.Collections.Generic;

class Program {
    // Returns maximum possible equal sum of three stacks
    // with removal of top elements allowed
    static int MaxEqualSum(int N1, int N2, int N3,
                           List<int> S1, List<int> S2,
                           List<int> S3)
    {
        List<int> suffix = new List<int>(S3.Count + 1);

        int sum1 = 0;
        // HashSet<int> st1 will contain all elements of
        // suffix sum of stack1
        HashSet<int> st1 = new HashSet<int>();

        // calculating suffix sum of stack1 and inserting it
        // into HashSet st1
        for (int i = S1.Count - 1; i >= 0; i--) {
            sum1 = sum1 + S1[i];
            st1.Add(sum1);
        }

        int sum2 = 0;
        // HashSet<int> st2 will contain all elements of
        // suffix sum of stack2
        HashSet<int> st2 = new HashSet<int>();

        // calculating suffix sum of stack2 and inserting it
        // into HashSet st2
        for (int i = S2.Count - 1; i >= 0; i--) {
            sum2 = sum2 + S2[i];
            st2.Add(sum2);
        }

        // calculating suffix sum of stack3 and storing in
        // suffix list
        for (int i = S3.Count - 1; i >= 0; i--) {
            suffix.Insert(
                0,
                S3[i] + (suffix.Count > 0 ? suffix[0] : 0));
        }

        // find the maximum suffix sum which is present in
        // all three stacks
        foreach(int s in suffix)
        {
            if (st1.Contains(s) && st2.Contains(s)) {
                return s;
            }
        }
        return 0;
    }

    // Driven Program
    static void Main(string[] args)
    {
        List<int> stack1 = new List<int>{ 3, 2, 1, 1, 1 };
        List<int> stack2 = new List<int>{ 4, 3, 2 };
        List<int> stack3 = new List<int>{ 1, 1, 4, 1 };

        Console.WriteLine(MaxEqualSum(
            stack1.Count, stack2.Count, stack3.Count,
            stack1, stack2, stack3));
    }
}
// This code is contributed by shivamgupta0987654321
JavaScript
// Java program to calculate maximum sum with equal
// stack sum.

// Function to calculate the maximum possible equal 
// sum of three stacks
// with removal of top elements allowed
function maxEqualSum(N1, N2, N3, S1, S2, S3) {
    let suffix = new Array(S3.length + 1).fill(0);
    
    let sum1 = 0;
    let st1 = new Set();

    // Calculating suffix sum of stack1 and inserting it into Set st1
    for (let i = S1.length - 1; i >= 0; i--) {
        sum1 = sum1 + S1[i];
        st1.add(sum1);
    }

    let sum2 = 0;
    let st2 = new Set();

    // Calculating suffix sum of stack2 and inserting it into Set st2
    for (let i = S2.length - 1; i >= 0; i--) {
        sum2 = sum2 + S2[i];
        st2.add(sum2);
    }

    // Calculating suffix sum of stack3 and storing it in the 
    // suffix array
    for (let i = S3.length - 1; i >= 0; i--) {
        suffix[i] = suffix[i + 1] + S3[i];
    }

    // Finding the maximum suffix sum which is present in all 
    // three stacks
    for (let i = 0; i < suffix.length; i++) {
        if (st1.has(suffix[i]) && st2.has(suffix[i])) {
            return suffix[i];
        }
    }

    return 0; // If no equal sum is found
}

// Driven Program
let stack1 = [3, 2, 1, 1, 1];
let stack2 = [4, 3, 2];
let stack3 = [1, 1, 4, 1];

console.log(maxEqualSum(stack1.length, stack2.length, 
stack3.length, stack1, stack2, stack3));
// THIS CODE IS CONTRIBUTED BY YASH AGARWAL(YASHAGARWAL2852002)

Output
5

Time Complexity : O(n1+ n2 + n3) where n1, n2 and n3 are sizes of three stacks. As we have different loops for each stack.
Auxiliary space: O(n1+n2+n3) because we are storing the prefix sums



Previous Article
Next Article

Similar Reads

Find three element from given three arrays such that their sum is X | Set 2
Given three sorted integer arrays A[], B[] and C[], the task is to find three integers, one from each array such that they sum up to a given target value X. Print Yes or No depending on whether such triplet exists or not.Examples: Input: A[] = {2}, B[] = {1, 6, 7}, C[] = {4, 5}, X = 12 Output: Yes A[0] + B[1] + C[0] = 2 + 6 + 4 = 12Input: A[] = {2}
9 min read
Find three element from different three arrays such that a + b + c = sum
Given three integer arrays and a "sum", the task is to check if there are three elements a, b, c such that a + b + c = sum and a, b and c belong to three different arrays. Examples : Input : a1[] = { 1 , 2 , 3 , 4 , 5 }; a2[] = { 2 , 3 , 6 , 1 , 2 }; a3[] = { 3 , 2 , 4 , 5 , 6 }; sum = 9 Output : Yes 1 + 2 + 6 = 9 here 1 from a1[] and 2 from a2[] a
15+ min read
Maximum count of integers to be chosen from given two stacks having sum at most K
Given two stacks stack1[] and stack2[] of size N and M respectively and an integer K, The task is to count the maximum number of integers from two stacks having sum less than or equal to K. Examples: Input: stack1[ ] = { 60, 90, 120 }stack2[ ] = { 100, 10, 10, 250 }, K = 130Output: 3Explanation: Take 3 numbers from stack1 which are 100 and 10 and 1
9 min read
Find minimum sum such that one of every three consecutive elements is taken
Given an array of n non-negative numbers, the task is to find the minimum sum of elements (picked from the array) such that at least one element is picked out of every 3 consecutive elements in the array. Examples : Input : arr[] = {1, 2, 3} Output : 1 Input : arr[] = {1, 2, 3, 6, 7, 1} Output : 4 We pick 3 and 1 (3 + 1 = 4) Note that there are fol
9 min read
Check if two Stacks are equal or not without alteration
Given two Stacks S1 and S2, the task is to check if both the stacks are equal or not in the same order without losing the original stacks. If both the stacks are equal, then print "Yes ". Otherwise, print "No". Examples: Input: S1 = {3, 4, 2, 1}, S2 = {3, 4, 2, 1}Output: Yes Input: S1 = {3, 4, 6}, S2 = {7, 2, 1}Output: No Approach: The given proble
8 min read
Split array to three subarrays such that sum of first and third subarray is equal and maximum
Given an array of N integers, the task is to print the sum of the first subarray by splitting the array into exactly three subarrays such that the sum of the first and third subarray elements are equal and the maximum. Note: All the elements must belong to a subarray and the subarrays can also be empty. Examples: Input: a[] = {1, 3, 1, 1, 4} Output
13 min read
Find three closest elements from given three sorted arrays
Given three sorted arrays A[], B[] and C[], find 3 elements i, j and k from A, B and C respectively such that max(abs(A[i] - B[j]), abs(B[j] - C[k]), abs(C[k] - A[i])) is minimized. Here abs() indicates absolute value. Example : Input : A[] = {1, 4, 10} B[] = {2, 15, 20} C[] = {10, 12} Output: 10 15 10Explanation: 10 from A, 15 from B and 10 from C
15+ min read
Find three integers less than or equal to N such that their LCM is maximum
Given a number N(>=3). The task is to find the three integers (<=N) such that LCM of these three integers is maximum. Examples: Input: N = 3 Output: 1 2 3 Input: N = 5 Output: 3 4 5 Recommended PracticeLCM TripletTry It! Approach: Since the task is to maximize the LCM, so if all three numbers don't have any common factor then the LCM will be
6 min read
Find a triplet from three linked lists with sum equal to a given number
Given three linked lists, say a, b and c, find one node from each list such that the sum of the values of the nodes is equal to a given number. For example, if the three linked lists are 12->6->29, 23->5->8, and 90->20->59, and the given number is 101, the output should be triple "6 5 90".In the following solutions, size of all th
14 min read
Maximize sum of topmost elements of S stacks by popping at most N elements
Given S stacks of length M, the task is to maximize the sum of elements at the top of each stack by popping at most N elements.Example: Input: S = 1, N = 3, stacks = { 5, 1, 2, 8, 9 } Output: 8 Explanation: Maximum 3 elements can be removed. The current element at the top of the stack is 5. On removal of 5, the new element at the top is 1. On remov
15+ min read
Number of quadruples where the first three terms are in AP and last three terms are in GP
Given an array arr[] of N integers. The task is to find the number of index quadruples (i, j, k, l) such that a[i], a[j] and a[k] are in AP and a[j], a[k] and a[l] are in GP. All the quadruples have to be distinct.Examples: Input: arr[] = {2, 6, 4, 9, 2} Output: 2 Indexes of elements in the quadruples are (0, 2, 1, 3) and (4, 2, 1, 3) and correspon
9 min read
Maximum sum subarray having sum less than or equal to given sum
Given an array of non-negative integers and a sum. We have to find sum of the subarray having a maximum sum less than or equal to the given sum in the array. Note: Given array contains only non-negative integers. Examples: Input: arr[] = { 1, 2, 3, 4, 5 } sum = 11Output: 10Subarray having maximum sum is { 1, 2, 3, 4 }Input: arr[] = { 2, 4, 6, 8, 10
10 min read
Split array in three equal sum subarrays
Consider an array A of n integers. Determine if array A can be split into three consecutive parts such that sum of each part is equal. If yes then print any index pair(i, j) such that sum(arr[0..i]) = sum(arr[i+1..j]) = sum(arr[j+1..n-1]), otherwise print -1. Examples: Input : arr[] = {1, 3, 4, 0, 4} Output : (1, 2) Sum of subarray arr[0..1] is equ
14 min read
Partition the array into three equal sum segments
Given an array of n integers, we have to partition the array into three segments such that all the segments have an equal sum. Segment sum is the sum of all the elements in the segment. Examples: Input : 1, 3, 6, 2, 7, 1, 2, 8 Output : [1, 3, 6], [2, 7, 1], [2, 8] Input : 7, 6, 1, 7 Output : [7], [6, 1], [7] Input : 7, 6, 2, 7 Output : Cannot divid
12 min read
Count the number of ways to divide an array into three contiguous parts having equal sum
Given an array of n numbers. Our task is to find out the number of ways to divide the array into three contiguous parts such that the sum of three parts is equal. In other words, we need to find the number of index pairs i and j such that sum of elements from 0 to i-1 is equal to the sum of elements from i to j is equal to the sum of elements from
15+ min read
Javascript Program For Finding A Triplet From Three Linked Lists With Sum Equal To A Given Number
Given three linked lists, say a, b and c, find one node from each list such that the sum of the values of the nodes is equal to a given number. For example, if the three linked lists are 12->6->29, 23->5->8, and 90->20->59, and the given number is 101, the output should be triple "6 5 90".In the following solutions, size of all th
4 min read
Find maximum subset sum formed by partitioning any subset of array into 2 partitions with equal sum
Given an array A containing N elements. Partition any subset of this array into two disjoint subsets such that both the subsets have an identical sum. Obtain the maximum sum that can be obtained after partitioning. Note: It is not necessary to partition the entire array, that is any element might not contribute to any of the partition. Examples: In
15+ min read
Print numbers such that no two consecutive numbers are co-prime and every three consecutive numbers are co-prime
Given an integer N, the task is to print N integers ? 109 such that no two consecutive of these integers are co-prime and every 3 consecutive are co-prime. Examples: Input: N = 3 Output: 6 15 10Input: N = 4 Output: 6 15 35 14 Approach: We can just multiply consecutive primes and for the last number just multiply the gcd(last, last-1) * 2. We do thi
15+ min read
Coin game winner where every player has three choices
A and B are playing a game. In the beginning, there are n coins. Given two more numbers x and y. In each move, a player can pick x or y or 1 coin. A always starts the game. The player who picks the last coin wins the game or the person who is not able to pick any coin loses the game. For a given value of n, find whether A will win the game or not i
8 min read
Sorting array using Stacks
Given an array of elements, the task is to sort these elements using a stack. Prerequisites: Stacks Examples: Input : 8 5 7 1 9 12 10 Output : 1 5 7 8 9 10 12 Explanation : Output is sorted element set Input : 7 4 10 20 2 5 9 1 Output : 1 2 4 5 7 9 10 20 We basically use Sort a stack using a temporary stack. Then we put sorted stack elements back t
6 min read
Merging and Sorting Two Unsorted Stacks
Given 2 input stacks with elements in an unsorted manner. Problem is to merge them into a new final stack, such that the elements become arranged in a sorted manner. Examples: Input : s1 : 9 4 2 1 s2: 8 17 3 10 Output : final stack: 1 2 3 4 8 9 10 17 Input : s1 : 5 7 2 6 4 s2 : 12 9 3 Output : final stack: 2 3 4 5 6 7 9 12 Create an empty stack to
6 min read
Infix to Prefix conversion using two stacks
Infix: An expression is called the Infix expression if the operator appears in between the operands in the expression. Simply of the form (operand1 operator operand2). Example : (A+B) * (C-D) Prefix: An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 ope
13 min read
Sudo Placement[1.3] | Playing with Stacks
You are given 3 stacks, A(Input Stack), B(Auxiliary Stack) and C(Output Stack). Initially stack A contains numbers from 1 to N, you need to transfer all the numbers from stack A to stack C in sorted order i.e in the end, the stack C should have smallest element at the bottom and largest at top. You can use stack B i.e at any time you can push/pop e
7 min read
Add two numbers represented by Stacks
Given two numbers N1 and N2 represented by two stacks, such that their most significant digits are present at the bottom of the stack, the task is to calculate and return the sum of the two numbers in the form of a stack. Examples: Input: N1={5, 8, 7, 4}, N2={2, 1, 3} Output: {6, 0, 8, 7}Explanation:Step 1: Popped element from N1(= 4) + Popped elem
8 min read
Minimum number of stacks possible using boxes of given capacities
Given N boxes with their capacities which denotes the total number of boxes that it can hold above it. You can stack up the boxes one over the other as long as the total number of boxes above each box is less than or equal to its capacity. Find the minimum number of stacks that can be made by using all the boxes. Examples: Input: arr[] = {0, 0, 1,
7 min read
Reversing a Stack using two empty Stacks
Given a stack S, the task is to reverse the stack S using two additional stacks. Example: Input: S={1, 2, 3, 4, 5}Output: 5 4 3 2 1Explanation:The initial stack S:1→top2345After reversing it, use two additional stacks:5→top4321 Input: S={1, 25, 17}Output: 17 25 1 Approach: Follow the steps below to solve the problem: Create two additional empty sta
6 min read
Largest Rectangle Area under Histogram using JavaScript | Without using Stacks
Find the largest rectangular area possible in a given histogram where the largest rectangle can be made of a number of contiguous bars. For simplicity, assume that all bars have the same width and the width is 1 unit. For example, consider the following histogram with 7 bars of heights {6, 2, 5, 4, 5, 1, 6}. The largest possible rectangle possible
2 min read
How does memory stacks work in Javascript ?
Introduction: The memory stack is a mechanism in JavaScript that allows us to allocate and free memory. If a programmer wants to store some data, they must first create an empty part of the heap that is called a "stack." Then, they can push and then pop values on the stack. When working with strings in JavaScript, we typically use string concatenat
3 min read
Implement Dynamic Multi Stack (K stacks) using only one Data Structure
In this article, we will see how to create a data structure that can handle multiple stacks with growable size. The data structure needs to handle three operations: push(x, stackNum) = pushes value x to the stack numbered stackNumpop(stackNum) = pop the top element from the stack numbered stackNumtop(stackNum) = shows the topmost element of the sta
15+ min read
Check if the two given stacks are same
Given two Stacks, the task is to check if the given stacks are same or not.Two stacks are said to be same if they contains the same elements in the same order.Example: Approach: Take a flag variable and set it to true initially, flag = true. This variable will indicate whether the stacks are same or not.First check if the size of given stack1 and s
6 min read
Article Tags :
Practice Tags :