The Wayback Machine - https://web.archive.org/web/20240818163940/https://www.geeksforgeeks.org/maximum-equilibrium-sum-in-an-array/
Open In App

Maximum equilibrium sum in an array

Last Updated : 19 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given an array arr[]. Find the maximum value of prefix sum which is also suffix sum for index i in arr[].

Examples : 

Input : arr[] = {-1, 2, 3, 0, 3, 2, -1}
Output : 4
Prefix sum of arr[0..3] =
Suffix sum of arr[3..6]

Input : arr[] = {-2, 5, 3, 1, 2, 6, -4, 2}
Output : 7
Prefix sum of arr[0..3] =
Suffix sum of arr[3..7]

A Simple Solution is to one by one check the given condition (prefix sum equal to suffix sum) for every element and returns the element that satisfies the given condition with maximum value. 

C++
// CPP program to find 
// maximum equilibrium sum.
#include <bits/stdc++.h>
using namespace std;

// Function to find 
// maximum equilibrium sum.
int findMaxSum(int arr[], int n)
{
    int res = INT_MIN;
    for (int i = 0; i < n; i++)
    {
    int prefix_sum = arr[i];
    for (int j = 0; j < i; j++)
        prefix_sum += arr[j];

    int suffix_sum = arr[i];
    for (int j = n - 1; j > i; j--)
        suffix_sum += arr[j];

    if (prefix_sum == suffix_sum)
        res = max(res, prefix_sum);
    }
    return res;
}

// Driver Code
int main()
{
    int arr[] = {-2, 5, 3, 1, 
                  2, 6, -4, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findMaxSum(arr, n);
    return 0;
}
Java
// java program to find maximum
// equilibrium sum.
import java.io.*;

class GFG {
    
    // Function to find maximum 
    // equilibrium sum.
    static int findMaxSum(int []arr, int n)
    {
        int res = Integer.MIN_VALUE;
        
        for (int i = 0; i < n; i++)
        {
            int prefix_sum = arr[i];
            
            for (int j = 0; j < i; j++)
                prefix_sum += arr[j];
        
            int suffix_sum = arr[i];
            
            for (int j = n - 1; j > i; j--)
                suffix_sum += arr[j];
        
            if (prefix_sum == suffix_sum)
                res = Math.max(res, prefix_sum);
        }
        
        return res;
    }
    
    // Driver Code
    public static void main (String[] args)
    {
        int arr[] = {-2, 5, 3, 1, 2, 6, -4, 2 };
        int n = arr.length;
        System.out.println(findMaxSum(arr, n));
    }
}

// This code is contributed by anuj_67.
Python3
# Python 3 program to find maximum 
# equilibrium sum.
import sys

# Function to find maximum equilibrium sum.
def findMaxSum(arr, n):
    res = -sys.maxsize - 1
    for i in range(n):
        prefix_sum = arr[i]
        for j in range(i):
            prefix_sum += arr[j]

        suffix_sum = arr[i]
        j = n - 1
        while(j > i):
            suffix_sum += arr[j]
            j -= 1
        if (prefix_sum == suffix_sum):
            res = max(res, prefix_sum)

    return res

# Driver Code
if __name__ == '__main__':
    arr = [-2, 5, 3, 1, 2, 6, -4, 2]
    n = len(arr)
    print(findMaxSum(arr, n))

# This code is contributed by
# Surendra_Gangwar
C#
// C# program to find maximum
// equilibrium sum.
using System;

class GFG {
    
    // Function to find maximum 
    // equilibrium sum.
    static int findMaxSum(int []arr, int n)
    {
        int res = int.MinValue;
        
        for (int i = 0; i < n; i++)
        {
            int prefix_sum = arr[i];
            
            for (int j = 0; j < i; j++)
                prefix_sum += arr[j];
        
            int suffix_sum = arr[i];
            
            for (int j = n - 1; j > i; j--)
                suffix_sum += arr[j];
        
            if (prefix_sum == suffix_sum)
                res = Math.Max(res, prefix_sum);
        }
        
        return res;
    }
    
    // Driver Code
    public static void Main ()
    {
        int []arr = {-2, 5, 3, 1, 2, 6, -4, 2 };
        int n = arr.Length;
        Console.WriteLine(findMaxSum(arr, n));
    }
}

// This code is contributed by anuj_67.
JavaScript
<script>

// Javascript program to find 
// maximum equilibrium sum.

// Function to find 
// maximum equilibrium sum.
function findMaxSum(arr, n)
{
    var res = -1000000000;
    for (var i = 0; i < n; i++)
    {
    var prefix_sum = arr[i];
    for (var j = 0; j < i; j++)
        prefix_sum += arr[j];

    var suffix_sum = arr[i];
    for (var j = n - 1; j > i; j--)
        suffix_sum += arr[j];

    if (prefix_sum == suffix_sum)
        res = Math.max(res, prefix_sum);
    }
    return res;
}

// Driver Code
var arr = [-2, 5, 3, 1, 
              2, 6, -4, 2 ];
var n = arr.length;
document.write( findMaxSum(arr, n));

</script>
PHP
<?php
// PHP program to find
// maximum equilibrium sum.

// Function to find 
// maximum equilibrium sum.
function findMaxSum( $arr, $n)
{
    $res = PHP_INT_MIN;
    for ( $i = 0; $i < $n; $i++)
    {
    $prefix_sum = $arr[$i];
    for ( $j = 0; $j < $i; $j++)
        $prefix_sum += $arr[$j];

    $suffix_sum = $arr[$i];
    for ( $j = $n - 1; $j > $i; $j--)
        $suffix_sum += $arr[$j];

    if ($prefix_sum == $suffix_sum)
        $res = max($res, $prefix_sum);
    }
    return $res;
}

// Driver Code
$arr = array(-2, 5, 3, 1,
              2, 6, -4, 2 );
$n = count($arr);
echo findMaxSum($arr, $n);

// This code is contributed by anuj_67.
?>

Output
7

Time Complexity: O(n2) 
Auxiliary Space: O(n)

A Better Approach is to traverse the array and store prefix sum for each index in array presum[], in which presum[i] stores sum of subarray arr[0..i]. Do another traversal of the array and store suffix sum in another array suffsum[], in which suffsum[i] stores sum of subarray arr[i..n-1]. After this for each index check if presum[i] is equal to suffsum[i] and if they are equal then compare their value with the overall maximum so far. 

C++
// CPP program to find 
// maximum equilibrium sum.
#include <bits/stdc++.h>
using namespace std;

// Function to find maximum
// equilibrium sum.
int findMaxSum(int arr[], int n)
{
    // Array to store prefix sum.
    int preSum[n];

    // Array to store suffix sum.
    int suffSum[n];

    // Variable to store maximum sum.
    int ans = INT_MIN;

    // Calculate prefix sum.
    preSum[0] = arr[0];
    for (int i = 1; i < n; i++) 
        preSum[i] = preSum[i - 1] + arr[i]; 

    // Calculate suffix sum and compare
    // it with prefix sum. Update ans
    // accordingly.
    suffSum[n - 1] = arr[n - 1];
    if (preSum[n - 1] == suffSum[n - 1])
        ans = max(ans, preSum[n - 1]);
        
    for (int i = n - 2; i >= 0; i--) 
    {
        suffSum[i] = suffSum[i + 1] + arr[i];
        if (suffSum[i] == preSum[i]) 
            ans = max(ans, preSum[i]);     
    }

    return ans;
}

// Driver Code
int main()
{
    int arr[] = { -2, 5, 3, 1,
                   2, 6, -4, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findMaxSum(arr, n);
    return 0;
}
Java
// Java program to find maximum equilibrium sum.
import java.io.*;

public class GFG {
    

    // Function to find maximum
    // equilibrium sum.
    static int findMaxSum(int []arr, int n)
    {
        
        // Array to store prefix sum.
        int []preSum = new int[n];
    
        // Array to store suffix sum.
        int []suffSum = new int[n];
    
        // Variable to store maximum sum.
        int ans = Integer.MIN_VALUE;
    
        // Calculate prefix sum.
        preSum[0] = arr[0];
        for (int i = 1; i < n; i++) 
            preSum[i] = preSum[i - 1] + arr[i]; 
    
        // Calculate suffix sum and compare
        // it with prefix sum. Update ans
        // accordingly.
        suffSum[n - 1] = arr[n - 1];
        
        if (preSum[n - 1] == suffSum[n - 1])
            ans = Math.max(ans, preSum[n - 1]);
            
        for (int i = n - 2; i >= 0; i--) 
        {
            suffSum[i] = suffSum[i + 1] + arr[i];
            
            if (suffSum[i] == preSum[i]) 
                ans = Math.max(ans, preSum[i]); 
        }
    
        return ans;
    }
    
    // Driver Code
    static public void main (String[] args)
    {
        int []arr = { -2, 5, 3, 1, 2, 6, -4, 2 };
        int n = arr.length;
        
        System.out.println( findMaxSum(arr, n));
    }
}

// This code is contributed by anuj_67
Python
# Python3 program to find
# maximum equilibrium sum.

# Function to find maximum
# equilibrium sum.
def findMaxSum(arr, n):

    # Array to store prefix sum.
    preSum = [0 for i in range(n)]

    # Array to store suffix sum.
    suffSum = [0 for i in range(n)]

    # Variable to store maximum sum.
    ans = -10000000

    # Calculate prefix sum.
    preSum[0] = arr[0]
    
    for i in range(1, n):
    
        preSum[i] = preSum[i - 1] + arr[i]

    # Calculate suffix sum and compare
    # it with prefix sum. Update ans
    # accordingly.
    suffSum[n - 1] = arr[n - 1]
    if (preSum[n - 1] == suffSum[n - 1]):
        ans = max(ans, preSum[n - 1])
     
    for i in range(n - 2, -1, -1):
        suffSum[i] = suffSum[i + 1] + arr[i]
        if (suffSum[i] == preSum[i]):
            ans = max(ans, preSum[i])
    
    return ans

# Driver Code
if __name__=='__main__':

    arr = [-2, 5, 3, 1,2, 6, -4, 2]
    n = len(arr)
    print(findMaxSum(arr, n))
    
# This code is contributed by pratham76
C#
// C# program to find maximum equilibrium sum.
using System;

public class GFG {
    

    // Function to find maximum
    // equilibrium sum.
    static int findMaxSum(int []arr, int n)
    {
        
        // Array to store prefix sum.
        int []preSum = new int[n];
    
        // Array to store suffix sum.
        int []suffSum = new int[n];
    
        // Variable to store maximum sum.
        int ans = int.MinValue;
    
        // Calculate prefix sum.
        preSum[0] = arr[0];
        for (int i = 1; i < n; i++) 
            preSum[i] = preSum[i - 1] + arr[i]; 
    
        // Calculate suffix sum and compare
        // it with prefix sum. Update ans
        // accordingly.
        suffSum[n - 1] = arr[n - 1];
        
        if (preSum[n - 1] == suffSum[n - 1])
            ans = Math.Max(ans, preSum[n - 1]);
            
        for (int i = n - 2; i >= 0; i--) 
        {
            suffSum[i] = suffSum[i + 1] + arr[i];
            
            if (suffSum[i] == preSum[i]) 
                ans = Math.Max(ans, preSum[i]); 
        }
    
        return ans;
    }
    
    // Driver Code
    static public void Main ()
    {
        int []arr = { -2, 5, 3, 1, 2, 6, -4, 2 };
        int n = arr.Length;
        
        Console.WriteLine( findMaxSum(arr, n));
    }
}

// This code is contributed by anuj_67
JavaScript
<script>

// Javascript program to find 
// maximum equilibrium sum.

// Function to find maximum
// equilibrium sum.
function findMaxSum(arr, n)
{
     
    // Array to store prefix sum.
    let preSum = new Array(n);
    preSum.fill(0);
 
    // Array to store suffix sum.
    let suffSum = new Array(n);
    suffSum.fill(0);
 
    // Variable to store maximum sum.
    let ans = Number.MIN_VALUE;
 
    // Calculate prefix sum.
    preSum[0] = arr[0];
    for(let i = 1; i < n; i++)
        preSum[i] = preSum[i - 1] + arr[i];
 
    // Calculate suffix sum and compare
    // it with prefix sum. Update ans
    // accordingly.
    suffSum[n - 1] = arr[n - 1];
     
    if (preSum[n - 1] == suffSum[n - 1])
        ans = Math.max(ans, preSum[n - 1]);
         
    for(let i = n - 2; i >= 0; i--)
    {
        suffSum[i] = suffSum[i + 1] + arr[i];
         
        if (suffSum[i] == preSum[i])
            ans = Math.max(ans, preSum[i]);
    }
    return ans;
}

// Driver code
let arr = [ -2, 5, 3, 1, 2, 6, -4, 2 ];
let n = arr.length;

document.write(findMaxSum(arr, n));

// This code is contributed by rameshtravel07

</script>
PHP
<?php
// PHP program to find maximum equilibrium sum.

// Function to find maximum equilibrium sum.
function findMaxSum($arr, $n)
{
    // Array to store prefix sum.
    $preSum[$n] = array();

    // Array to store suffix sum.
    $suffSum[$n] = array();

    // Variable to store maximum sum.
    $ans = PHP_INT_MIN;

    // Calculate prefix sum.
    $preSum[0] = $arr[0];
    for ($i = 1; $i < $n; $i++) 
        $preSum[$i] = $preSum[$i - 1] + $arr[$i]; 

    // Calculate suffix sum and compare
    // it with prefix sum. Update ans
    // accordingly.
    $suffSum[$n - 1] = $arr[$n - 1];
    if ($preSum[$n - 1] == $suffSum[$n - 1])
        $ans = max($ans, $preSum[$n - 1]);
        
    for ($i = $n - 2; $i >= 0; $i--) 
    {
        $suffSum[$i] = $suffSum[$i + 1] + $arr[$i];
        if ($suffSum[$i] == $preSum[$i]) 
            $ans = max($ans, $preSum[$i]); 
    }

    return $ans;
}

// Driver Code
$arr = array( -2, 5, 3, 1, 2, 6, -4, 2 );
$n = sizeof($arr);
echo findMaxSum($arr, $n);

// This code is contributed by ajit.
?>

Output
7

Time Complexity: O(n) 
Auxiliary Space: O(n)

Further Optimization : 
We can avoid the use of extra space by first computing the total sum, then using it to find the current prefix and suffix sums.

Steps to solve this problem:

  1. Initialize two variables sum and prefix_sum to 0.
  2. Sum is the sum of all elements of the arr array, calculated using the accumulate function. prefix_sum is used to keep track of the sum of the elements of the subarray.
  3. Initialize a variable res to INT_MIN, which will store the maximum sum of the subarray such that the sum of the elements of the subarray is equal to the sum of the elements of the rest of the array.
  4. Loop through the array arr from index 0 to index n-1.
  5. For each iteration of the loop, increment the value of prefix_sum by the current element of the arr array.
  6. If prefix_sum is equal to sum, update the value of res to be the maximum of res and prefix_sum.
  7. Decrement the value of sum by the current element of the arr array.
  8. Repeat steps 5-7 for all elements of the arr array.
  9. After the loop, return the value of res. 

Implementation:

C++
// CPP program to find
// maximum equilibrium sum.
#include <bits/stdc++.h>
using namespace std;

// Function to find 
// maximum equilibrium sum.
int findMaxSum(int arr[], int n)
{
    int sum = accumulate(arr, arr + n, 0);
    int prefix_sum = 0, res = INT_MIN;
    for (int i = 0; i < n; i++)
    {
    prefix_sum += arr[i]; 
    if (prefix_sum == sum)
        res = max(res, prefix_sum); 
    sum -= arr[i];
    }
    return res;
}

// Driver Code
int main()
{
    int arr[] = { -2, 5, 3, 1, 
                   2, 6, -4, 2 };
    int n = sizeof(arr) / sizeof(arr[0]);
    cout << findMaxSum(arr, n);
    return 0;
}
Java
// Java program to find maximum equilibrium
// sum.
import java.lang.Math.*;
import java.util.stream.*;

class GFG {
    
    // Function to find maximum equilibrium
    // sum.
    static int findMaxSum(int arr[], int n)
    {
        int sum = IntStream.of(arr).sum();
        int prefix_sum = 0,
        res = Integer.MIN_VALUE;
        
        for (int i = 0; i < n; i++)
        {
            prefix_sum += arr[i]; 
            
            if (prefix_sum == sum)
                res = Math.max(res, prefix_sum); 
            sum -= arr[i];
        }
        
        return res;
    }
    
    // Driver Code
    public static void main(String[] args)
    {
        int arr[] = { -2, 5, 3, 1, 
                    2, 6, -4, 2 };
        int n = arr.length;
        System.out.print(findMaxSum(arr, n));
    }
}

// This code is contributed by Smitha.
Python
# Python3 program to find
# maximum equilibrium sum.
import sys

# Function to find 
# maximum equilibrium sum. 
def findMaxSum(arr,n):
    
    ss = sum(arr)
    prefix_sum = 0
    res = -sys.maxsize
    
    for i in range(n):
        prefix_sum += arr[i]
        
        if prefix_sum == ss:
            res = max(res, prefix_sum); 
            
        ss -= arr[i];
        
    return res
 
# Driver code   
if __name__=="__main__":
    
    arr = [ -2, 5, 3, 1, 
             2, 6, -4, 2 ]
    n = len(arr)
    
    print(findMaxSum(arr, n))

# This code is contributed by rutvik_56
C#
// C# program to find maximum equilibrium sum.
using System.Linq;
using System;

class GFG {
    
    static int Add(int x, int y) { 
        return x + y; 
    } 
    
    // Function to find maximum equilibrium
    // sum.
    static int findMaxSum(int []arr, int n)
    {
        int sum = arr.Aggregate(func:Add);
        int prefix_sum = 0,
        res = int.MinValue;
        
        for (int i = 0; i < n; i++)
        {
            prefix_sum += arr[i]; 
            
            if (prefix_sum == sum)
                res = Math.Max(res, prefix_sum); 
            sum -= arr[i];
        }
        
        return res;
    }
    
    // Driver Code
    public static void Main()
    {
        int []arr = { -2, 5, 3, 1, 
                    2, 6, -4, 2 };
        int n = arr.Length;
        Console.Write(findMaxSum(arr, n));
    }
}

// This code is contributed by Smitha.
JavaScript
<script>    
// javascript program to find
// maximum equilibrium sum.

// Function to find
// maximum equilibrium sum.
function findMaxSum(arr,n)
{
    let sum = 0;
  for(let i=0; i < n; i++)
  {
     sum = sum + arr[i];
  } 
    let prefix_sum = 0, res = Number.MIN_VALUE;
    for (let i = 0; i < n; i++)
    {
    prefix_sum += arr[i];
    if (prefix_sum == sum)
        res = Math.max(res, prefix_sum);
    sum -= arr[i];
    }
    return res;
}

// Driver Code

    let arr = [ -2, 5, 3, 1,
                2, 6, -4, 2 ];
    let n = arr.length;
    document.write(findMaxSum(arr, n));
    
    // This code is contributed by vaibhavrabadiya117.
</script>
PHP
<?php

function findMaxSum($arr, $n) {
  $sum = array_sum($arr);
  $prefixSum = 0;
  $res = PHP_INT_MIN; // Use PHP constant for minimum integer value

  for ($i = 0; $i < $n; $i++) {
    $prefixSum += $arr[$i];
    if ($prefixSum === $sum) {
      $res = max($res, $prefixSum);
    }
    $sum -= $arr[$i];
  }

  return $res;
}

// Driver Code
$arr = [-2, 5, 3, 1, 2, 6, -4, 2];
$n = count($arr);

$maxSum = findMaxSum($arr, $n);
echo $maxSum;

?>

Output
7

Time Complexity: O(n) 
Auxiliary Space: O(1)
 



Previous Article
Next Article

Similar Reads

Python3 Program for Maximum equilibrium sum in an array
Given an array arr[]. Find the maximum value of prefix sum which is also suffix sum for index i in arr[]. Examples : Input : arr[] = {-1, 2, 3, 0, 3, 2, -1} Output : 4 Prefix sum of arr[0..3] = Suffix sum of arr[3..6] Input : arr[] = {-2, 5, 3, 1, 2, 6, -4, 2} Output : 7 Prefix sum of arr[0..3] = Suffix sum of arr[3..7] A Simple Solution is to one
3 min read
Javascript Program for Maximum equilibrium sum in an array
Given an array arr[]. Find the maximum value of prefix sum which is also suffix sum for index i in arr[]. Examples : Input : arr[] = {-1, 2, 3, 0, 3, 2, -1} Output : 4 Prefix sum of arr[0..3] = Suffix sum of arr[3..6] Input : arr[] = {-2, 5, 3, 1, 2, 6, -4, 2} Output : 7 Prefix sum of arr[0..3] = Suffix sum of arr[3..7] A Simple Solution is to one
4 min read
Minimum integer to be appended to convert given Array into equilibrium
Given an array A[] of length N, the task is to find the minimum integer to be appended at any end in the array to make it equilibrium. An array is in equilibrium if there exists any index i such that:sum of A[0, . . ., i-1] = sum of A[i+1, . . ., N-1] Example: Input: A[] = {5, 2, 6, 4, 3, 2} Output: 2 Explanation: In the above array integer 2 is ad
8 min read
Longest equilibrium Subarray of given Array
Given an integer array arr of size N[], the task is to find the longest equilibrium subarray i.e. a subarray such that the prefix sum of the remaining array is the same as the suffix sum. Examples: Input: N = 3, arr[] = {10, 20, 10}Output: 1Explanation: The longest subarray is {20}. The remaining prefix is {10} and suffix is {10}.Therefore only one
8 min read
Python3 Program for Equilibrium index of an array
Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in an array A: Example : Input: A[] = {-7, 1, 5, 2, -4, 3, 0} Output: 3 3 is an equilibrium index, because: A[0] + A[1] + A[2] = A[4] + A[5] + A[6] Input: A[] = {1, 2, 3} Output: -1 Write a functio
4 min read
Javascript Program for Equilibrium index of an array
Write a function int equilibrium(int[] arr, int n); that given a sequence arr[] of size n, returns an equilibrium index (if any) or -1 if no equilibrium indexes exist. The equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in an array A: Example :
5 min read
Equilibrium index of an array
Given an array arr[] of size n, return an equilibrium index (if any) or -1 if no equilibrium index exists. The equilibrium index of an array is an index such that the sum of elements at lower indexes equals the sum of elements at higher indexes. Note: Return equilibrium point in 1-based indexing. Return -1 if no such point exists. Examples: Input:
15 min read
Check if the given vectors are at equilibrium or not
Given the x, y and z coordinates of three vectors, the task is to check if they are at equilibrium or not.Examples: Input: x1 = -2, y1 = 1, z1 = 0, x2 = 5, y2 = 0, z2 = 5, x3 = -3, y3 = -1, z3 = -5 Output: The vectors are at equilibrium.Input: x1 = 2, y1 = -17, z1 = 0, x2 = 5, y2 = 1, z2 = -5, x3 = 4, y3 = 2, z3 = -4 Output: The vectors are not at
7 min read
Program to check if a body is in equilibrium or not
Given a 2D array a[][] where each row consists of N vector coordinates of the form (xi, yi, zi) of an applied body. If the body is in equilibrium, print "YES". Otherwise, print "NO". Examples: Input: a[][] = {{4, 1, 7}, {-2, 4, -1}, {1, -5, -3}}Output: NO Input: a[][] = {{3, -1, 7}, {-5, 2, -4}, {2, -1, -3}}Output: YES Approach: Follow the steps be
5 min read
Minimize removal from front or end to make the Binary String at equilibrium
Given a binary string S of size N, the task is to find the minimum number of removal required either from the start or end position from the binary strings such that the count of '0' and '1' becomes equal in the final string after removal. Examples: Input: S = "0111010"Output: 3Explanation: Remove 3 elements from the front of given string. String a
8 min read
Maximum sum subarray having sum less than given sum using Set
Given an array arr[] of length N and an integer K, the task is the find the maximum sum subarray with a sum less than K.Note: If K is less than the minimum element, then return INT_MIN. Examples: Input: arr[] = {-1, 2, 2}, K = 4 Output: 3 Explanation: The subarray with maximum sum which is less than 4 is {-1, 2, 2}. The subarray {2, 2} has maximum
7 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
Find an element in array such that sum of left array is equal to sum of right array
Given, an array of size n. Find an element that divides the array into two sub-arrays with equal sums. Examples: Input: 1 4 2 5 0Output: 2Explanation: If 2 is the partition, subarrays are : [1, 4] and [5] Input: 2 3 4 1 4 5Output: 1Explanation: If 1 is the partition, Subarrays are : [2, 3, 4] and [4, 5] Input: 1 2 3Output: -1Explanation: No sub-arr
15+ min read
Maximum XOR value of maximum and second maximum element among all possible subarrays
Given an array arr[] of N distinct positive integers, let's denote max(i, j) and secondMax(i, j) as the maximum and the second maximum element of the subarray arr[i...j]. The task is to find the maximum value of max(i, j) XOR secondMax(i, j) for all possible values of i and j. Note that the size of the subarray must be at least two.Examples: Input:
5 min read
Divide array in two Subsets such that sum of square of sum of both subsets is maximum
Given an integer array arr[], the task is to divide this array into two non-empty subsets such that the sum of the square of the sum of both the subsets is maximum and sizes of both the subsets must not differ by more than 1.Examples: Input: arr[] = {1, 2, 3} Output: 26 Explanation: Sum of Subset Pairs are as follows (1)2 + (2 + 3)2 = 26 (2)2 + (1
6 min read
Maximum sum of Array formed by replacing each element with sum of adjacent elements
Given an array arr[] of size N, the task is to find the maximum sum of the Array formed by replacing each element of the original array with the sum of adjacent elements.Examples: Input: arr = [4, 2, 1, 3] Output: 23 Explanation: Replacing each element of the original array with the sum of adjacent elements: 4 + 2 = 6 6 + 1 = 7 7 + 3 = 10 Array for
9 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
Modify array to another given array by replacing array elements with the sum of the array
Given an array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. If found to be true, then print "YES". Otherwise, print "NO". Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 }
13 min read
Modify array to another given array by replacing array elements with the sum of the array | Set-2
Given an Array input[] consisting only of 1s initially and an array target[] of size N, the task is to check if the array input[] can be converted to target[] by replacing input[i] with the sum of array elements in each step. Examples: Input: input[] = { 1, 1, 1 }, target[] = { 9, 3, 5 } Output: YES Explanation: Replacing input[1] with (input[0] +
10 min read
Maximum subarray sum in array formed by repeating the given array k times
Given an integer k and an integer array arr[] of n elements, the task is to find the largest sub-array sum in the modified array (formed by repeating the given array k times). For example, if arr[] = {1, 2} and k = 3 then the modified array will be {1, 2, 1, 2, 1, 2}. Examples: Input: arr[] = {1, 2}, k = 3 Output: 9 Modified array will be {1, 2, 1,
12 min read
Maximum sub-array sum after dividing array into sub-arrays based on the given queries
Given an array arr[] and an integer k, we can cut this array at k different positions where k[] stores the positions of all the cuts required. The task is to print maximum sum among all the cuts after every cut made. Every cut is of the form of an integer x where x denotes a cut between arr[x] and arr[x + 1]. Examples: Input: arr[] = {4, 5, 6, 7, 8
9 min read
Sum of elements in 1st array such that number of elements less than or equal to them in 2nd array is maximum
Given two unsorted arrays arr1[] and arr2[], the task is to find the sum of elements of arr1[] such that the number of elements less than or equal to them in arr2[] is maximum. Examples: Input: arr1[] = {1, 2, 3, 4, 7, 9}, arr2[] = {0, 1, 2, 1, 1, 4} Output: 20 Below table shows the count of elements in arr2[] which are ? the elements of arr1[] arr
15 min read
Maximize maximum possible subarray sum of an array by swapping with elements from another array
Given two arrays arr[] and brr[] consisting of N and K elements respectively, the task is to find the maximum subarray sum possible from the array arr[] by swapping any element from the array arr[] with any element of the array brr[] any number of times. Examples: Input: N = 5, K = 4, arr[] = { 7, 2, -1, 4, 5 }, brr[] = { 1, 2, 3, 2 }Output : 21Exp
7 min read
Maximum removals possible from an array such that sum of its elements is greater than or equal to that of another array
Given two arrays arr[] and brr[] of size N and M respectively, the task is to count the maximum number of elements that can be removed from the array arr[] such that the sum of elements in arr[] is greater than or equal to the sum of elements in brr[]. Examples: Input: arr[] = { 1, 2, 4, 6 }, brr[] = { 7 } Output: 2 Explanation: Removing arr[2] mod
8 min read
Generate an N-length array having maximum element minimized and sum of array elements divisible by K
Given two positive integers N and K, the task is to minimize the maximum element of the array formed such that the sum of array elements is positive and divisible by K. Examples: Input: N = 4, K = 50Output: 13Explanation The generated array is {12, 13, 12, 13}. Sum of the array is 50, which is divisible by K (= 50). Maximum element present in the a
3 min read
Construct an Array of size N with sum divisible by K and array maximum is minimized
Given integers N and K. The task is to construct an array of size N such that sum of all elements is divisible by K and the maximum element is as minimum as possible. Note: There can be many possible arrays. Printing any one of them is acceptable Examples: Input: N = 1, K = 5Output: 5Explanation: Sum of all elements = 5 and 5 is divisible by 5. Inp
8 min read
Maximum possible sum of a window in an array such that elements of same window in other array are unique
Given two arrays A and B of equal number of elements. The task is to find the maximum sum possible of a window in array B such that elements of same window in A[] are unique. Examples: Input: A = [0, 1, 2, 3, 0, 1, 4] B = [9, 8, 1, 2, 3, 4, 5] Output: sum = 20 The maximum sum possible in B[] such that all corresponding elements in A[] are unique is
10 min read
Maximum subset sum having difference between its maximum and minimum in range [L, R]
Given an array arr[] of N positive integers and a range [L, R], the task is to find the maximum subset-sum such that the difference between the maximum and minimum elements of the subset lies in the given range. Examples: Input: arr[] = {6, 5, 0, 9, 1}, L = 0, R = 3Output: 15Explanation: The subset {6, 9} of the given array has the difference betwe
9 min read
Maximum length Subsequence with alternating sign and maximum Sum
Given an array arr[] of size n having both positive and negative integer excluding zero. The task is to find the subsequence with an alternating sign having maximum size and maximum sum that is, in a subsequence sign of each adjacent element is opposite for example if the first one is positive then the second one has to be negative followed by anot
7 min read
Sum of maximum of all subarrays by adding even frequent maximum twice
Given an array arr[] consisting of N integers (All array elements are a perfect power of 2), the task is to calculate the sum of the maximum elements in all the subarrays. Note: If the frequency of the maximum element in a subarray is even, add twice the value of that element to the sum. Examples: Input: arr[] = {1, 2}Output: 5Explanation: All poss
15+ min read
Article Tags :
Practice Tags :
three90RightbarBannerImg