Given count of digits 1, 2, 3, 4, find the maximum sum possible
Given the count of digits 1, 2, 3, 4. Using these digits you are allowed to only form numbers 234 and 12. The task is to find the maximum possible sum that can be obtained after forming the numbers.
Note: The aim is only to maximize the sum, even if some of the digits left unused.
Examples:
Input : c1 = 5, c2 = 2, c3 = 3, c4 = 4
Output : 468
Explanation : We can form two 234s
Input : c1 = 5, c2 = 3, c3 = 1, c4 = 5
Output : 258
Explanation : We can form one 234 and two 12s
Approach : An efficient approach is to first try to make 234’s. The possible number of 234s are minimum of c2, c3, c4. After this, with remaining 1’s and 2’s try to form 12s.
Below is the implementation of the above approach :
C++
#include <bits/stdc++.h>
using namespace std;
int Maxsum( int c1, int c2, int c3, int c4)
{
int sum = 0;
int two34 = min(c2, min(c3, c4));
sum = two34 * 234;
c2 -= two34;
sum += min(c2, c1) * 12;
return sum;
}
int main()
{
int c1 = 5, c2 = 2, c3 = 3, c4 = 4;
cout << Maxsum(c1, c2, c3, c4);
return 0;
}
|
Java
class GFG
{
static int Maxsum( int c1, int c2, int c3, int c4)
{
int sum = 0 ;
int two34 = Math.min(c2,Math.min(c3, c4));
sum = two34 * 234 ;
c2 -= two34;
sum +=Math.min(c2, c1) * 12 ;
return sum;
}
public static void main(String[] args)
{
int c1 = 5 , c2 = 2 , c3 = 3 , c4 = 4 ;
System.out.println(Maxsum(c1, c2, c3, c4));
}
}
|
Python3
def Maxsum(c1, c2, c3, c4):
sum = 0
two34 = min (c2, min (c3, c4))
sum = two34 * 234
c2 - = two34
sum + = min (c2, c1) * 12
return sum
c1 = 5 ; c2 = 2 ; c3 = 3 ; c4 = 4
print (Maxsum(c1, c2, c3, c4))
|
C#
using System;
class GFG
{
static int Maxsum( int c1, int c2, int c3, int c4)
{
int sum = 0;
int two34 = Math.Min(c2, Math.Min(c3, c4));
sum = two34 * 234;
c2 -= two34;
sum +=Math.Min(c2, c1) * 12;
return sum;
}
public static void Main()
{
int c1 = 5, c2 = 2, c3 = 3, c4 = 4;
Console.WriteLine(Maxsum(c1, c2, c3, c4));
}
}
|
PHP
<?php
function Maxsum( $c1 , $c2 , $c3 , $c4 )
{
$sum = 0;
$two34 = min( $c2 , min( $c3 , $c4 ));
$sum = $two34 * 234;
$c2 -= $two34 ;
$sum += min( $c2 , $c1 ) * 12;
return $sum ;
}
$c1 = 5; $c2 = 2;
$c3 = 3; $c4 = 4;
echo Maxsum( $c1 , $c2 , $c3 , $c4 );
?>
|
Javascript
<script>
function Maxsum(c1,c2,c3,c4)
{
let sum = 0;
let two34 = Math.min(c2,Math.min(c3, c4));
sum = two34 * 234;
c2 -= two34;
sum +=Math.min(c2, c1) * 12;
return sum;
}
let c1 = 5, c2 = 2, c3 = 3, c4 = 4;
document.write(Maxsum(c1, c2, c3, c4));
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Last Updated :
09 Jun, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...