The Wayback Machine - https://web.archive.org/web/20240910052556/https://www.geeksforgeeks.org/sum-of-bit-differences-among-all-pairs/
Open In App

Sum of bit differences among all pairs

Last Updated : 05 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Medium
60.03%
52.7K

Given an integer array of n integers, find sum of bit differences in all pairs that can be formed from array elements. Bit difference of a pair (x, y) is count of different bits at same positions in binary representations of x and y. 

For example, bit difference for 2 and 7 is 2. Binary representation of 2 is 010 and 7 is 111 ( first and last bits differ in two numbers). 

Examples :  

Input: arr[] = {1, 2}
Output: 4
All pairs in array are (1, 1), (1, 2)
                       (2, 1), (2, 2)
Sum of bit differences = 0 + 2 +
                         2 + 0
                      = 4

Input:  arr[] = {1, 3, 5}
Output: 8
All pairs in array are (1, 1), (1, 3), (1, 5)
                       (3, 1), (3, 3) (3, 5),
                       (5, 1), (5, 3), (5, 5)
Sum of bit differences =  0 + 1 + 1 +
                          1 + 0 + 2 +
                          1 + 2 + 0 
                       = 8

Source: Google Interview Question

Naive Solution:

A Simple Solution is to run two loops to consider all pairs one by one. For every pair, count bit differences. Finally return sum of counts. Time complexity of this solution is O(n2). We are using bitset::count() which is an inbuilt STL in C++ which returns the number of set bits in the binary representation of a number. 

C++




// C++ program to compute sum of pairwise bit differences
#include <bits/stdc++.h>
using namespace std;
  
int sum_bit_diff(vector<int> a)
{
    int n = a.size();
    int ans = 0;
  
    for (int i = 0; i < n - 1; i++) {
        int count = 0;
  
        for (int j = i; j < n; j++) {
            // Bitwise and of pair (a[i], a[j])
            int x = a[i] & a[j];
            // Bitwise or of pair (a[i], a[j])
            int y = a[i] | a[j];
  
            bitset<32> b1(x);
            bitset<32> b2(y);
  
            // to count set bits in and of two numbers
            int r1 = b1.count();
            // to count set bits in or of two numbers
            int r2 = b2.count();
  
            // Absolute differences at individual bit positions of two
            // numbers is contributed by pair (a[i], a[j]) in count
            count = abs(r1 - r2);
  
            // each pair adds twice of contributed count
            // as both (a, b) and (b, a) are considered
            // two separate pairs.
            ans = ans + (2 * count);
        }
    }
    return ans;
}
  
int main()
{
  
    vector<int> nums{ 10, 5 };
    int ans = sum_bit_diff(nums);
  
    cout << ans;
}


Java




/*package whatever //do not write package name here */
  
import java.io.*;
  
class GFG {
    
    static int sumBitDiff(int[] arr){
        int diff = 0;                                //hold the ans
            
          for(int i=0; i<arr.length; i++){
            for(int j=i; j<arr.length; j++){
                
              //XOR toggles the bits and will form a number that will have
              //set bits at the places where the numbers bits differ
              //eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2
                
                 int xor = arr[i]^arr[j];
                  int count = countSetBits(xor);        //Integer.bitCount() can also be used
                    
                  //when i == j (same numbers) the xor would be 0, 
                  //thus our ans will remain unaffected as (2*0 = 0)
                  diff += 2*count;
            }
        }
        
          return diff;
    }
    
    //Kernighan algo
      static int countSetBits(int n){
        int count = 0;            // `count` stores the total bits set in `n`
   
        while (n != 0) {
            n = n & (n - 1);    // clear the least significant bit set
            count++;
        }
   
        return count;
    }
    
    public static void main (String[] args) {
        int[] arr = {5,10};
          int ans  = sumBitDiff(arr);
        System.out.println(ans);
    }
}


Python3




# Python3 program for the above approach
def sumBitDiff(arr):
    diff = 0    #hold the ans
        
    for i in range(len(arr)):
        for j in range(i, len(arr)):
                
        # XOR toggles the bits and will form a number that will have
        # set bits at the places where the numbers bits differ
        # eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2           
            xor = arr[i]^arr[j]
            count = countSetBits(xor)        #Integer.bitCount() can also be used
                    
            # when i == j (same numbers) the xor would be 0, 
            # thus our ans will remain unaffected as (2*0 = 0)
            diff += (2*count)
        
    return diff
      
# Kernighan algo
def countSetBits(n):
    count = 0            # `count` stores the total bits set in `n`
   
    while (n != 0) :
        n = n & (n - 1)    # clear the least significant bit set
        count += 1
          
    return count
      
# Driver code
if __name__ == "__main__":
      
    arr = [5,10]
    ans  = sumBitDiff(arr)
    print(ans)
  
    # This code is contributed by sanjoy_62.


C#




/*package whatever //do not write package name here */
  
using System;
  
public class GFG {
    
    static int sumBitDiff(int[] arr){
        int diff = 0;                                //hold the ans
            
          for(int i=0; i<arr.Length; i++){
            for(int j=i; j<arr.Length; j++){
                
              //XOR toggles the bits and will form a number that will have
              //set bits at the places where the numbers bits differ
              //eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2
                
                 int xor = arr[i]^arr[j];
                  int count = countSetBits(xor);        //int.bitCount() can also be used
                    
                  //when i == j (same numbers) the xor would be 0, 
                  //thus our ans will remain unaffected as (2*0 = 0)
                  diff += 2*count;
            }
        }
        
          return diff;
    }
    
    //Kernighan algo
      static int countSetBits(int n){
        int count = 0;            // `count` stores the total bits set in `n`
   
        while (n != 0) {
            n = n & (n - 1);    // clear the least significant bit set
            count++;
        }
   
        return count;
    }
    
    public static void Main(String[] args) {
        int[] arr = {5,10};
          int ans  = sumBitDiff(arr);
        Console.WriteLine(ans);
    }
}
  
// This code contributed by umadevi9616 


Javascript




<script>
  
// javascript program for above approach
    function sumBitDiff(arr)
    {
        let diff = 0;                                
        // hold the ans
            
          for(let i = 0; i < arr.length; i++){
            for(let j = i; j < arr.length; j++){
                
              // XOR toggles the bits and will form a number that will have
              // set bits at the places where the numbers bits differ
              // eg: 010 ^ 111 = 101...diff of bits = count of 1's = 2
                
                 let xor = arr[i]^arr[j];
                  let count = countSetBits(xor);        
                  // Integer.bitCount() can also be used
                    
                  // when i == j (same numbers) the xor would be 0, 
                  // thus our ans will remain unaffected as (2*0 = 0)
                  diff += 2*count;
            }
        }
        
          return diff;
    }
    
    // Kernighan algo
      function countSetBits(n){
        let count = 0;            // `count` stores the total bits set in `n`
   
        while (n != 0) {
            n = n & (n - 1);    // clear the least significant bit set
            count++;
        }
   
        return count;
    }
  
  
// Driver code
    let arr = [5,10];
    let ans  = sumBitDiff(arr);
    document.write(ans);
      
    // This code is contributed by splevel62.
</script>


Output

8

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

Efficient Solution :

An Efficient Solution can solve this problem in O(n) time using the fact that all numbers are represented using 32 bits (or some fixed number of bits). The idea is to count differences at individual bit positions. We traverse from 0 to 31 and count numbers with i’th bit set. Let this count be ‘count’. There would be “n-count” numbers with i’th bit not set. So count of differences at i’th bit would be “count * (n-count) * 2”, the reason for this formula is as every pair having one element which has set bit at i’th position and second element having unset bit at i’th position contributes exactly 1 to sum, therefore total permutation count will be count*(n-count) and multiply by 2 is due to one more repetition of all this type of pair as per given condition for making pair 1<=i, j<=N.

Below is implementation of above idea.  

C++




// C++ program to compute sum of pairwise bit differences
#include <bits/stdc++.h>
using namespace std;
  
int sumBitDifferences(int arr[], int n)
{
    int ans = 0; // Initialize result
    // traverse over all bits
    for (int i = 0; i < 32; i++) {
        // count number of elements with i'th bit set
        int count = 0;
        for (int j = 0; j < n; j++)
            if ((arr[j] & (1 << i)))
                count++;
        // Add "count * (n - count) * 2" to the answer
        ans += (count * (n - count) * 2);
    }
    return ans;
}
  
// Driver program
int main()
{
    int arr[] = { 1, 3, 5 };
    int n = sizeof arr / sizeof arr[0];
    cout << sumBitDifferences(arr, n) << endl;
    return 0;
}
  
// This code is contributed by Sania Kumari Gupta (kriSania804)


C




// C program to compute sum of pairwise bit differences
#include <stdio.h>
  
int sumBitDifferences(int arr[], int n)
{
    int ans = 0; // Initialize result
    // traverse over all bits
    for (int i = 0; i < 32; i++) {
        // count number of elements with i'th bit set
        int count = 0;
        for (int j = 0; j < n; j++)
            if ((arr[j] & (1 << i)))
                count++;
        // Add "count * (n - count) * 2" to the answer
        ans += (count * (n - count) * 2);
    }
    return ans;
}
  
// Driver program
int main()
{
    int arr[] = { 1, 3, 5 };
    int n = sizeof arr / sizeof arr[0];
    printf("%d\n", sumBitDifferences(arr, n));
    return 0;
}
  
// This code is contributed by Sania Kumari Gupta (kriSania804)


Java




// Java program to compute sum of pairwise
// bit differences
  
import java.io.*;
class GFG {
    static int sumBitDifferences(int arr[], int n)
    {
        int ans = 0; // Initialize result
        // traverse over all bits
        for (int i = 0; i < 32; i++) {
            // count number of elements with i'th bit set
            int count = 0;
            for (int j = 0; j < n; j++)
                if ((arr[j] & (1 << i)) != 0)
                    count++;
            // Add "count * (n - count) * 2"
            // to the answer...(n - count = unset bit count)
            ans += (count * (n - count) * 2);
        }
        return ans;
    }
  
    // Driver program
    public static void main(String args[])
    {
        int arr[] = { 1, 3, 5 };
        int n = arr.length;
        System.out.println(sumBitDifferences(arr, n));
    }
}
  
// This code is contributed by Sania Kumari Gupta (kriSania804)


Python3




# Python program to compute sum of pairwise bit differences
  
def sumBitDifferences(arr, n):
  
    ans = 0  # Initialize result
  
    # traverse over all bits
    for i in range(0, 32):
      
        # count number of elements with i'th bit set
        count = 0
        for j in range(0, n):
            if ( (arr[j] & (1 << i)) ):
                count+= 1
  
        # Add "count * (n - count) * 2" to the answer
        ans += (count * (n - count) * 2);
      
    return ans
  
# Driver program
arr = [1, 3, 5]
n = len(arr )
print(sumBitDifferences(arr, n))
  
# This code is contributed by
# Smitha Dinesh Semwal    


C#




// C# program to compute sum
// of pairwise bit differences
using System;
  
class GFG {
    static int sumBitDifferences(int[] arr,
                                 int n)
    {
        int ans = 0; // Initialize result
  
        // traverse over all bits
        for (int i = 0; i < 32; i++) {
  
            // count number of elements
            // with i'th bit set
            int count = 0;
            for (int j = 0; j < n; j++)
                if ((arr[j] & (1 << i)) != 0)
                    count++;
  
            // Add "count * (n - count) * 2"
            // to the answer
            ans += (count * (n - count) * 2);
        }
  
        return ans;
    }
    // Driver Code
    public static void Main()
    {
  
        int[] arr = { 1, 3, 5 };
        int n = arr.Length;
  
        Console.Write(sumBitDifferences(arr, n));
    }
}
  
// This code is contributed by ajit


PHP




<?php
// PHP program to compute sum
// of pairwise bit differences
  
function sumBitDifferences($arr, $n)
{
    // Initialize result
    $ans = 0; 
  
    // traverse over all bits
    for ($i = 0; $i < 32; $i++)
    {
        // count number of elements
        // with i'th bit set
        $count = 0;
        for ($j = 0; $j < $n; $j++)
            if (($arr[$j] & (1 << $i)))
                $count++;
  
        // Add "count * (n - count) * 2"
        // to the answer
        $ans += ($count * ($n - 
                           $count) * 2);
    }
  
    return $ans;
}
  
// Driver Code
$arr = array(1, 3, 5);
$n = sizeof($arr);
echo sumBitDifferences($arr, $n), "\n";
  
// This code is contributed by m_kit
?>


Javascript




<script>
  
// Javascript program to compute sum
// of pairwise bit differences
function sumBitDifferences(arr, n)
{
      
    // Initialize result
    let ans = 0; 
  
    // Traverse over all bits
    for(let i = 0; i < 32; i++) 
    {
          
        // count number of elements with i'th bit set
        let count = 0;
        for(let j = 0; j < n; j++)
            if ((arr[j] & (1 << i)))
                count++;
  
        // Add "count * (n - count) * 2" to the answer
        ans += (count * (n - count) * 2);
    }
    return ans;
}
  
// Driver code
let arr = [ 1, 3, 5 ];
let n = arr.length;
  
document.write(sumBitDifferences(arr, n));
  
// This code is contributed by subhammahato348
  
</script>


Output

8

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

Asked in: Google

Thanks to Gaurav Ahirwar for suggesting this solution.



Similar Reads

Sum of consecutive bit differences of first N non-negative integers
Given a positive integer N, the task is to find out the sum of all consecutive bit differences from 0 to N. Note: If the bit length is different for two numbers like(3, 4) then append 0 at the beginning (011, 100). Examples: Input: N = 3 Output: 4 Explanation: Bit differences of (0, 1) + (1, 2) + (2, 3) = 1 + 2 + 1 = 4.Input: N = 7 Output: 11 Naive
8 min read
Sum of bit differences for numbers from 0 to N | Set 2
Given a number N, the task is to calculate the total number of corresponding different bit in the binary representation for every consecutive number from 0 to N. Examples: Input: N = 5 Output: 8 Explanation: Binary Representation of numbers are: 0 -&gt; 000, 1 -&gt; 001, 2 -&gt; 010, 3 -&gt; 011, 4 -&gt; 100, 5 -&gt; 101 Between 1 and 0 -&gt; 1 bit
7 min read
Find a number with least sum of bit differences from given Array
Given an array arr[] and an integer L which represents the number of bits to be considered in bit representation of an array element. The task is to find a positive integer X, such that the sum of the bit difference of all the elements in arr[] with X is minimum. Examples: Input: N = 3, L = 5, arr[] = {18, 9, 21}Output: 17Explanation: arr[1] = (18)
8 min read
Sum of bit differences for numbers from 0 to N
Given a number N, the task is to calculate the total number of corresponding different bit in the binary representation for every consecutive number from 0 to N.Examples: Input: N = 5 Output: 8 Explanation: Binary Representation of numbers are: 0 -&gt; 000, 1 -&gt; 001, 2 -&gt; 010, 3 -&gt; 011, 4 -&gt; 100, 5 -&gt; 101 Between 1 and 0 -&gt; 1 bit
8 min read
Minimum sum of all differences between unique pairs in the Array
Given an array arr[] consisting of N integers, the task is to find the minimum sum of all absolute differences between unique pairs of elements in the array after updating the array arr[]. To update the array, any two elements from the array can be chosen in any order. 1 is subtracted from the first element and added to the second element. This ste
7 min read
Sum of squares of differences between all pairs of an array
Given an array arr[] of size N, the task is to compute the sum of squares of differences of all possible pairs. Examples: Input: arr[] = {2, 8, 4}Output: 56Explanation: Sum of squared differences of all possible pairs = (2 - 8)2 + (2 - 4)2 + (8 - 4)2 = 56 Input: arr[] = {-5, 8, 9, -4, -3}Output: 950 Brute Force Approach: The brute force approach to
9 min read
Sum of absolute differences of all pairs in a given array
Given a sorted array of distinct elements, the task is to find the summation of absolute differences of all pairs in the given array. Examples: Input : arr[] = {1, 2, 3, 4} Output: 10 Sum of |2-1| + |3-1| + |4-1| + |3-2| + |4-2| + |4-3| = 10 Input : arr[] = {1, 8, 9, 15, 16} Output: 74 Input : arr[] = {1, 2, 3, 4, 5, 7, 9, 11, 14} Output: 188 A sim
11 min read
Maximum LCM among all pairs (i, j) of first N natural numbers
Given a positive integer N &gt; 1, the task is to find the maximum LCM among all the pairs (i, j) such that i &lt; j ? N.Examples: Input: N = 3 Output: 6 LCM(1, 2) = 2 LCM(1, 3) = 3 LCM(2, 3) = 6Input: N = 4 Output: 12 Approach: Since the LCM of two consecutive elements is equal to their multiples then it is obvious that the maximum LCM will be of
2 min read
Maximum LCM among all pairs (i, j) from the given Array
Given an array arr[], the task is to find the maximum LCM when the elements of the array are taken in pairs. Examples: Input: arr[] = {17, 3, 8, 6} Output: 136 Explanation: Respective Pairs with their LCM are: {8, 17} has LCM 136, {3, 17} has LCM 51, {6, 17} has LCM 102, {3, 8} has LCM 24, {3, 6} has LCM 6, and {6, 8} has LCM 24. Maximum LCM among
9 min read
Pair of integers having least GCD among all given pairs having GCD exceeding K
Given an array arr[][] containing pairs of integers in increasing order of GCDs, and an integer K, the task is to find a pair of integers whose GCD is at least K and is also the least among all possible GCDs exceeding K. If there exists no such pair, then print -1.Examples: Input: arr[][] = [(3, 6), (15, 30), (25, 75), (30, 120)], K = 16 Output: (2
7 min read
Maximum GCD among all pairs (i, j) of first N natural numbers
Given a positive integer N &gt; 1, the task is to find the maximum GCD among all the pairs (i, j) such that i &lt; j &lt; N.Examples: Input: N = 3Output: 3Explanation:All the possible pairs are: (1, 2) (1, 3) (2, 3) with GCD 1.Input: N = 4Output: 2Explanation:Out of all the possible pairs the pair with max GCD is (2, 4) with a value 2. Naive Approa
6 min read
Minimum and Maximum LCM among all pairs (i, j) in range [L, R]
Given two positive integers L and R representing a range. The task is to find the minimum and maximum possible LCM of any pair (i, j) in the range [L, R] such that L ≤ i &lt; j ≤ R. Examples: Input: L = 2, R = 6Output: 4 30Explanations: Following are the pairs with minimum and maximum LCM in range [2, 6].Minimum LCM --&gt; (2, 4) = 4Maximum LCM --
5 min read
Minimize increments required to make differences between all pairs of array elements even
Given an array, arr[] consisting of N integers, the task is to minimize the number of increments of array elements required to make all differences pairs of array elements even. Examples: Input: arr[] = {4, 1, 2}Output: 1Explanation: Operation 1: Increment arr[1] by 1. The array arr[] modifies to {4, 2, 2}.All pairs: (4, 2) ? difference = 2(4, 2) ?
5 min read
Find min and max values among all maximum leaf nodes from all possible Binary Max Heap
Given a positive integer N, the task is to find the largest and smallest elements, from the maximum leaf nodes of every possible binary max-heap formed by taking the first N natural numbers as the nodes' value of the binary max-heap. Examples: Input: N = 2Output: 1 1Explanation: There is only one maximum binary heap with the nodes {1, 2}: In the ab
7 min read
Maximum length intersection of all K ranges among all given ranges
Given an array arr[] consisting of N ranges of the form [L, R], the task is to select K ranges such that the intersection length of the K ranges is maximum. Examples: Input: arr[] = {{5, 15}, {1, 10}, {14, 50}, {30, 70}, {99, 100}}, K = 2Output: 21Explanation: Selecting ranges (14, 50) and (30, 70) would give the maximum answer. Therefore, the maxi
7 min read
Minimum sum of absolute differences of pairs in a triplet from three arrays
Given three arrays a[], b[] and c[] of sizes A, B and C respectively, the task is to find the minimum possible value of abs(a[i] - b[j]) + abs(b[j] - c[k]) where 0 ? i ? A, 0 ? j ? B and 0 ? k ? C. Examples: Input: A = 3, B = 2, C = 2, a[] = {1, 8, 5}, b[] = {2, 9}, c[] = {5, 4}Output: 3Explanation:The triplet (a[0], b[0], c[1]), i.e. (1, 2, 4) has
11 min read
Maximum sum of absolute differences between distinct pairs of a triplet from an array
Given an array arr[] consisting of N integers, the task is to find the maximum sum of absolute differences between all distinct pairs of the triplet in the array. Examples: Input: arr[] = {1, 2, 3, 4}Output: 6Explanation:The valid triplet is (1, 3, 4) as sum = |1 - 4| + |1 - 3| + |3 - 4| = 6, which is the maximum among all the triplets. Input: arr[
5 min read
Minimum sum of absolute differences between pairs of a triplet from an array
Given an array A[] consisting of positive integers, the task is to find the minimum value of |A[x] - A[y]| + |A[y] - A[z]| of any triplet (A[x], A[y], A[z]) from an array. Examples: Input: A[] = { 1, 1, 2, 3 }Output: 1Explanation:For x = 0, y = 1, z = 2|A[x] - A[y]| + |A[y] - A[z]| = 0 + 1 = 1, which is maximum possible Input : A[] = { 1, 1, 1 }Out
5 min read
Minimum and Maximum sum of absolute differences of pairs
Given an array of N integers where N is even, find the minimum and maximum sum of absolute difference of N/2 pairs formed by pairing every element with one other element. Examples: Input: a[] = {10, -10, 20, -40} Output: min_sum = 40, max_sum = 80 Explanation: Pairs selected for minimum sum (-10, -40) and (10, 20) min_sum = |-10 - -40| + |20 - 10|
8 min read
Sum of absolute differences of pairs from the given array that satisfy the given condition
Given an array arr[] of N elements, the task is to find the sum of absolute differences between all pairs (arr[i], arr[j]) such that i &lt; j and (j - i) is prime.Example: Input: arr[] = {1, 2, 3, 5, 7, 12} Output: 45 All valid index pairs are: (5, 0) -&gt; abs(12 - 1) = 11 (3, 0) -&gt; abs(5 - 1) = 4 (2, 0) -&gt; abs(3 - 1) = 2 (4, 1) -&gt; abs(7
12 min read
Find index of pair among given pairs with just greater average
Given an array of pairs arr[] of size N where the first value of all the pairs are distinct. For each pair of the given array find the index of another pair which have an average just greater than this one. Note: The average of two numbers a and b is defined as the floor ( a + b ) / 2. Examples: Input: { {2, 3}, {1, 3}, {3, 4} }Output: { 2, 2, -1}
11 min read
Count distinct XOR values among pairs using numbers in range 1 to N
Given a number N. The task is to count the number of distinct XOR of any possible pairs using numbers from 1 to N inclusive. Examples: Input: N = 3Output: 4Explanation: Following are the all possible pairs using elements from 1 to N inclusive.1^1 = 0 1^2 = 3 1^3 = 2 2^2 = 0 2^3 = 13^3 = 0 Therefore, there are 4 distinct possible XOR values. Input:
7 min read
Maximum sum of leaf nodes among all levels of the given binary tree
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum of leaf nodes among all level of the given binary tree.Examples: Input: 4 / \ 2 -5 / \ -1 3 Output: 2 Sum of all leaves at 0th level is 0. Sum of all leaves at 1st level is -5. Sum of all leaves at 2nd level is 2. Hence maximum sum is 2. Input: 1 / \ 2 3 / \
9 min read
Maximum sum of non-leaf nodes among all levels of the given binary tree
Given a Binary Tree having positive and negative nodes, the task is to find the maximum sum of non-leaf nodes among all levels of the given binary tree. Examples: Input: 4 / \ 2 -5 / \ -1 3 Output: 4 Sum of all non-leaf nodes at 0th level is 4. Sum of all non-leaf nodes at 1st level is 2. Sum of all non-leaf nodes at 2nd level is 0. Hence maximum s
9 min read
Split Array into K non-overlapping subset such that maximum among all subset sum is minimum
Given an array arr[] consisting of N integers and an integer K, the task is to split the given array into K non-overlapping subsets such that the maximum among the sum of all subsets is minimum. Examples: Input: arr[] = {1, 7, 9, 2, 12, 3, 3}, M = 3Output: 13Explanation:One possible way to split the array into 3 non-overlapping subsets is {arr[4],
7 min read
Maximum sum among all (a x b) submatrices for given Q queries
Given a matrix mat[][] of size N x M and an array queries[] of size Q, containing (a, b) pairs. The task is to find the maximum sum among all (a x b) sub-matrices of the matrix mat[][]. Note: The rows and columns of the sub-matrix must be contiguous. Examples: Input: N = 3, M = 4, Q = 1, queries[] = {(3, 2)} mat[][] = {{1, 2, 3, 9}, {4, 5, 6, 2}, {
15 min read
Maximum sum of segments among all segments formed in array after Q queries
Given two arrays arr[](1-based indexing) and queries[] consisting of N integers and queries[] contains a permutation of the first N natural numbers, the task is to perform the query on the array and find the maximum sum of segments among all segments formed such that in each query queries[i] the array element at index queries[i] is deleted and that
15 min read
Javascript Program for Maximum sum of i*arr[i] among all rotations of a given array
Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1. Examples: Input: arr[] = {8, 3, 1, 2} Output: 29 Explanation: Lets look at all the rotations, {8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11 {3, 1, 2, 8} = 3*0 + 1*1 + 2*2 + 8*3 = 29 {1, 2, 8, 3} = 1*0 + 2*1 + 8*2 + 3*3 = 27
7 min read
Maximum sum of values of nodes among all connected components of an undirected graph
Given an undirected graph with V vertices and E edges. Every node has been assigned a given value. The task is to find the connected chain with the maximum sum of values among all the connected components in the graph. Examples: Input: V = 7, E = 4 Values = {10, 25, 5, 15, 5, 20, 0}   Output : Max Sum value = 35 Explanation: Component {1, 2} - Valu
15+ min read
Maximum sum of i*arr[i] among all rotations of a given array
Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1. Examples: Input: arr[] = {8, 3, 1, 2} Output: 29 Explanation: Lets look at all the rotations, {8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11 {3, 1, 2, 8} = 3*0 + 1*1 + 2*2 + 8*3 = 29 {1, 2, 8, 3} = 1*0 + 2*1 + 8*2 + 3*3 = 27
15+ min read
Article Tags :