C++ Program to get largest sum we can make from 256 and 32 from digits


Suppose we have four numbers a, b, c and d. In a box there are some numeri digits. There are 'a' number of digits 2, 'b' number of digits 3, 'c' number of digits 5 and 'd' number of digits 6. We want to compose numbers 32 and 256 from these digits. We want to make the sum of these integers as large as possible. (Each digit can be used no more than once, and unused digits are not counted in the sum).

Problem Category

The above-mentioned problem can be solved by applying Greedy problem-solving techniques. The greedy algorithm techniques are types of algorithms where the current best solution is chosen instead of going through all possible solutions. Greedy algorithm techniques are also used to solve optimization problems, like its bigger brother dynamic programming. In dynamic programming, it is necessary to go through all possible subproblems to find out the optimal solution, but there is a drawback of it; that it takes more time and space. So, in various scenarios greedy technique is used to find out an optimal solution to a problem. Though it does not gives an optimal solution in all cases, if designed carefully it can yield a solution faster than a dynamic programming problem. Greedy techniques provide a locally optimal solution to an optimization problem. Examples of this technique include Kruskal's and Prim's Minimal Spanning Tree (MST) algorithm, Huffman Tree coding, Dijkstra's Single Source Shortest Path problem, etc.

https://www.tutorialspoint.com/data_structures_algorithms/greedy_algorithms.htm

https://www.tutorialspoint.com/data_structures_algorithms/dynamic_programming.htm

So, if the input of our problem is like a = 5; b = 1; c = 3; d = 4, then the output will be 800, because we can compose three integers 256 and one integer 32 to achieve the value 3 * 256 + 32 = 800.

Steps

To solve this, we will follow these steps −

x := minimum a, c and d
y := minimum of (a - x) and b
return (x * 256) + (y * 32)

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(int a, int b, int c, int d){
   int x = min(min(a, c), d);
   int y = min(a - x, b);
   return x * 256 + y * 32;
}
int main(){
   int a = 5;
   int b = 1;
   int c = 3;
   int d = 4;
   cout << solve(a, b, c, d) << endl;
}

Input

5, 1, 3, 4

Output

800

Updated on: 08-Apr-2022

78 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements