Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Maximum of sum of length of rectangles and squares formed by given sticks

  • Difficulty Level : Medium
  • Last Updated : 16 Jun, 2021

Given an array arr[] consisting of N integers, representing the length of the sticks, the task is to find the maximum sum possible of all lengths of the squares and rectangles constructed using these sticks. 
Note A single side can be represented using only a single stick.

Examples:

Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Input: arr[] = {5, 3, 2, 3, 6, 3, 3} 
Output: 12 
Sum of length of Squares= 3 * 4 = 12 
Sum of length of Rectangles = 0
Input: arr[] = {5, 3, 2, 3, 6, 4, 4, 4, 5, 5, 5 } 
Output: 34 
Sum of length of Squares = 5 * 4 = 20 
Sum of length of Rectangles = 3 * 2 + 4 * 2 = 34 
 

Approach: Follow the steps below to solve the problem:

  • Traverse the array to count the frequencies of all the array elements, say freq.
  • Count frequencies which are at least 2.
  • Convert frequencies to nearest smaller even value.
  • Convert the frequencies to single dimensional array in descending order.
  • Now, sum elements upto indices which are multiples of 4.
  • Print the sum all these elements

Below is the implementation of the above approach:

C++14




#include <bits/stdc++.h>
using namespace std;
 
// Function to find the maximum of sum
// of lengths of rectangles and squares
// formed using given set of sticks
void findSumLength(vector<int> arr,int n)
{
 
    // Stores the count of frequencies
    // of all the array elements
    map<int,int> freq;
    for(int i:arr) freq[i] += 1;
 
    // Stores frequencies which are at least 2
    map<int,int> freq_2;
 
    for (auto i:freq)
    {
        if (freq[i.first] >= 2)
            freq_2[i.first] = freq[i.first];
    }
   
    // Convert all frequencies to nearest
    // smaller even values.
    vector<int> arr1;
    for (auto i:freq_2)
        arr1.push_back((i.first) * (freq_2[(i.first)]/2)*2);
    sort(arr1.begin(), arr1.end());
 
    // Sum of elements up to
    // index of multiples of 4
    int summ = 0;
    for (int i:arr1)
        summ += i;
 
    // Print the sum
    cout << summ;
}
 
// Driver Code
int main()
{
  vector<int> arr = {5, 3, 2, 3, 6, 4, 4, 4, 5, 5, 5};
  int n = arr.size();
  findSumLength(arr, n);
  return 0;
}
 
// This code is contributed by mohit kumar 29.

Python3




# Python3 implementation of
# the above approach 
 
from collections import Counter
 
# Function to find the maximum of sum
# of lengths of rectangles and squares
# formed using given set of sticks
def findSumLength(arr, n) : 
     
    # Stores the count of frequencies
    # of all the array elements
    freq = dict(Counter(arr))
     
    # Stores frequencies which are at least 2
    freq_2 = {}
 
    for i in freq:
        if freq[i]>= 2:
            freq_2[i] = freq[i]
             
    # Convert all frequencies to nearest
    # smaller even values.
    arr1 = []
    for i in freq_2:
      arr1.extend([i]*(freq_2[i]//2)*2)
 
    # Sort the array in descending order
    arr1.sort(reverse = True)
 
    # Sum of elements up to
    # index of multiples of 4
    summ = 0
    for i in range((len(arr1)//4)*4):
        summ+= arr1[i]
         
    # Print the sum
    print(summ)
   
# Driver Code 
if __name__ == "__main__"
   
    arr = [5, 3, 2, 3, 6, 4, 4, 4, 5, 5, 5]; 
    n = len(arr); 
    findSumLength(arr, n);

C#




using System;
using System.Collections.Generic;
class GFG{
 
  // Function to find the maximum of sum
  // of lengths of rectangles and squares
  // formed using given set of sticks
  static void findSumLength(List<int> arr, int n)
  {
 
    // Stores the count of frequencies
    // of all the array elements
    Dictionary<int,int> freq = new Dictionary<int,int>();
    foreach (int i in arr){
      if(freq.ContainsKey(i))
        freq[i] += 1;
      else
        freq[i] = 1;
    }
 
    // Stores frequencies which are at least 2
    Dictionary<int,int> freq_2 = new Dictionary<int,int>();
    foreach(KeyValuePair<int, int> entry in freq)
    {
      if (freq[entry.Key] >= 2)
        freq_2[entry.Key] = freq[entry.Key];
    }
 
    // Convert all frequencies to nearest
    // smaller even values.
    List<int> arr1 = new List<int>();
    foreach(KeyValuePair<int, int> entry in freq_2)
      arr1.Add(entry.Key * (freq_2[entry.Key]/2)*2);
    arr1.Sort();
 
    // Sum of elements up to
    // index of multiples of 4
    int summ = 0;
    foreach (int i in arr1){
      summ += i;
    }
     
    // Print the sum
    Console.WriteLine(summ);
  }
 
  // Driver Code
  public static void Main()
  {
    List<int> arr = new List<int>(){5, 3, 2, 3, 6, 4, 4, 4, 5, 5, 5};
    int n = arr.Count;
    findSumLength(arr, n);
 
  }
}
 
// THIS CODE IS CONTRIBUTED BY SURENDRA_GANGWAR.

Javascript




<script>
 
// Function to find the maximum of sum
  // of lengths of rectangles and squares
  // formed using given set of sticks
function findSumLength(arr, n)
{
 
    // Stores the count of frequencies
    // of all the array elements
    let freq = new Map();
    for(let i = 0; i < arr.length; i++)
    {
          if(freq.has(arr[i]))
            freq.set(arr[i], freq.get(arr[i])+1);
          else
            freq.set(arr[i], 1);
    }
  
    // Stores frequencies which are at least 2
    let freq_2 = new Map();
    for(let [key, value] of freq.entries())
    {
          if (freq.get(key) >= 2)
              freq_2.set(key,freq.get(key));
    }
  
    // Convert all frequencies to nearest
    // smaller even values.
    let arr1 = [];
    for(let [key, value] of freq_2.entries())
          arr1.push(key * Math.floor(freq_2.get(key)/2)*2);
     
    arr1.sort(function(a, b){return a - b;});
      
    // Sum of elements up to
    // index of multiples of 4
    let summ = 0;
    for(let i = 0; i < arr1.length; i++){
      summ += arr1[i];
    }
      
    // Print the sum
    document.write(summ);
}
 
 // Driver Code
let arr=[5, 3, 2, 3, 6, 4, 4, 4, 5, 5, 5];
let n = arr.Count;
findSumLength(arr, n);
 
// This code is contributed by unknown2108
</script>
Output: 
34

 

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




My Personal Notes arrow_drop_up
Recommended Articles
Page :