Maximum of sum of length of rectangles and squares formed by given sticks
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:
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;
void findSumLength(vector< int > arr, int n)
{
map< int , int > freq;
for ( int i:arr) freq[i] += 1;
map< int , int > freq_2;
for ( auto i:freq)
{
if (freq[i.first] >= 2)
freq_2[i.first] = freq[i.first];
}
vector< int > arr1;
for ( auto i:freq_2)
arr1.push_back((i.first) * (freq_2[(i.first)]/2)*2);
sort(arr1.begin(), arr1.end());
int summ = 0;
for ( int i:arr1)
summ += i;
cout << summ;
}
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;
}
|
Java
import java.io.*;
import java.util.*;
class GFG
{
static void findSumLength( int [] arr, int n)
{
HashMap<Integer,Integer>freq = new HashMap<Integer,Integer>();
for ( int i:arr) {
if (freq.containsKey(i)){
freq.put(i, freq.get(i)+ 1 );
}
else {
freq.put(i, 1 );
}
}
HashMap<Integer,Integer>freq_2 = new HashMap<Integer,Integer>();
for (Map.Entry<Integer,Integer> i:freq.entrySet())
{
if (i.getValue() >= 2 )
freq_2.put(i.getKey() , i.getValue());
}
ArrayList<Integer>arr1 = new ArrayList<Integer>();
for (Map.Entry<Integer,Integer> i:freq_2.entrySet()){
arr1.add((i.getKey()) * (i.getValue()/ 2 )* 2 );
}
Collections.sort(arr1);
int summ = 0 ;
for ( int i:arr1)
summ += i;
System.out.println(summ);
}
public static void main(String args[])
{
int [] arr = { 5 , 3 , 2 , 3 , 6 , 4 , 4 , 4 , 5 , 5 , 5 };
int n = arr.length;
findSumLength(arr, n);
}
}
|
Python3
from collections import Counter
def findSumLength(arr, n) :
freq = dict (Counter(arr))
freq_2 = {}
for i in freq:
if freq[i]> = 2 :
freq_2[i] = freq[i]
arr1 = []
for i in freq_2:
arr1.extend([i] * (freq_2[i] / / 2 ) * 2 )
arr1.sort(reverse = True )
summ = 0
for i in range (( len (arr1) / / 4 ) * 4 ):
summ + = arr1[i]
print (summ)
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{
static void findSumLength(List< int > arr, int n)
{
Dictionary< int , int > freq = new Dictionary< int , int >();
foreach ( int i in arr){
if (freq.ContainsKey(i))
freq[i] += 1;
else
freq[i] = 1;
}
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];
}
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();
int summ = 0;
foreach ( int i in arr1){
summ += i;
}
Console.WriteLine(summ);
}
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);
}
}
|
Javascript
<script>
function findSumLength(arr, n)
{
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);
}
let freq_2 = new Map();
for (let [key, value] of freq.entries())
{
if (freq.get(key) >= 2)
freq_2.set(key,freq.get(key));
}
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;});
let summ = 0;
for (let i = 0; i < arr1.length; i++){
summ += arr1[i];
}
document.write(summ);
}
let arr=[5, 3, 2, 3, 6, 4, 4, 4, 5, 5, 5];
let n = arr.Count;
findSumLength(arr, n);
</script>
|
Time Complexity: O(NlogN)
Auxiliary Space: O(N)
Efficient Approach:-
- In this method we will store the frequency of the elements in a unordered_map.
- After this we will just go with every element frequency and if the frequency is greater than 1 then we will take this into our answer because for a particular stick to be in a answer we will be needed atleast 2 stick of that length so that atleast we can use it in a rectangle.
- But you may think that in this way how can we say that we will get actual answer, So we will not be getting actual answer but instead of this we will be getting greater answer as per required because let’s understand this with a example:-
- let’s say the array is {1,2,3,1,2,3} now we will take 1+1+2+2+3+3 = 12 into our answer but the actual answer is 2+2+3+3 = 10, So it means that in out answer we have used 6 sticks and to make a rectangle or a square we need 4 stick and 6 is not divisible by 4 so we need to remove two sticks form out answer, So to make answer maximum we will remove stick of length 1 and answer will become 12-2 = 10.
- This all the thing we will be implementing in our coding part.
Implementation:-
C++
#include <bits/stdc++.h>
using namespace std;
void findSumLength(vector< int > arr, int n)
{
int sum=0;
unordered_map< int , int > mm;
for ( auto x:arr)mm[x]++;
int mn=INT_MAX,total=0;
for ( auto x:mm){
int temp = x.second/2;
sum+=temp*2*(x.first);
total+=temp*2;
if (temp) mn=min(mn,x.first);
}
if (total%4){
sum-=mn*2;
}
cout << sum;
}
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;
}
|
Java
import java.util.*;
public class Main {
public static void findSumLength(ArrayList<Integer> arr, int n)
{
int sum = 0 ;
HashMap<Integer, Integer> mm = new HashMap<Integer, Integer>();
for ( int i = 0 ; i < n; i++) {
int x = arr.get(i);
if (mm.containsKey(x)) {
mm.put(x, mm.get(x) + 1 );
} else {
mm.put(x, 1 );
}
}
int mn = Integer.MAX_VALUE, total = 0 ;
for (Map.Entry<Integer, Integer> x : mm.entrySet()) {
int temp = x.getValue() / 2 ;
sum += temp * 2 * (x.getKey());
total += temp * 2 ;
if (temp > 0 ) {
mn = Math.min(mn, x.getKey());
}
}
if (total % 4 != 0 ) {
sum -= mn * 2 ;
}
System.out.print(sum);
}
public static void main(String[] args) {
ArrayList<Integer> arr = new ArrayList<Integer>(Arrays.asList( 5 , 3 , 2 , 3 , 6 , 4 , 4 , 4 , 5 , 5 , 5 ));
int n = arr.size();
findSumLength(arr, n);
}
}
|
Python3
def find_sum_length(arr):
sum_length = 0
mm = {}
for x in arr:
if x in mm:
mm[x] + = 1
else :
mm[x] = 1
mn = float ( 'inf' )
total = 0
for x in mm:
temp = mm[x] / / 2
sum_length + = temp * 2 * x
total + = temp * 2
if temp:
mn = min (mn, x)
if total % 4 :
sum_length - = mn * 2
return sum_length
if __name__ = = "__main__" :
arr = [ 5 , 3 , 2 , 3 , 6 , 4 , 4 , 4 , 5 , 5 , 5 ]
result = find_sum_length(arr)
print (result)
|
C#
using System;
using System.Collections.Generic;
class MainClass
{
public static void FindSumLength(List< int > arr, int n)
{
int sum = 0;
Dictionary< int , int > mm = new Dictionary< int , int >();
for ( int i = 0; i < n; i++)
{
int x = arr[i];
if (mm.ContainsKey(x))
{
mm[x]++;
}
else
{
mm[x] = 1;
}
}
int mn = int .MaxValue, total = 0;
foreach ( var x in mm)
{
int temp = x.Value / 2;
sum += temp * 2 * x.Key;
total += temp * 2;
if (temp > 0)
{
mn = Math.Min(mn, x.Key);
}
}
if (total % 4 != 0)
{
sum -= mn * 2;
}
Console.Write(sum);
}
public static void Main( string [] args)
{
List< int > arr = new List< int > { 5, 3, 2, 3, 6, 4, 4, 4, 5, 5, 5 };
int n = arr.Count;
FindSumLength(arr, n);
}
}
|
Javascript
<script>
function findSumLength(arr) {
let sum = 0;
const mm = new Map();
for (let i = 0; i < arr.length; i++) {
const x = arr[i];
if (mm.has(x)) {
mm.set(x, mm.get(x) + 1);
} else {
mm.set(x, 1);
}
}
let mn = Number.MAX_VALUE;
let total = 0;
mm.forEach((value, key) => {
const temp = Math.floor(value / 2);
sum += temp * 2 * key;
total += temp * 2;
if (temp > 0) {
mn = Math.min(mn, key);
}
});
if (total % 4 !== 0) {
sum -= mn * 2;
}
console.log(sum);
}
const arr = [5, 3, 2, 3, 6, 4, 4, 4, 5, 5, 5];
findSumLength(arr);
<script>
|
Time Complexity:- O(N), where N is the size of the array
Space Complexity:- O(N), where N is the size of the array
Last Updated :
08 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...