Digits and divisibility

2.5

2 votes
Open, Open, Medium, approved, Data Structures, Algorithms, Greedy algorithm, Open, Greedy algorithm, Greedy algorithm
Problem

You have been given a set of digits, where each digit in the set is distinct and lies in the range from 0 to 9 inclusive. You are required to create a Kdigit number from the set of digits that is given to you. Each digit from the set can be used for an arbitrary number of times to create the number.

You must create the number based on the following rule:

The number should be created in such a way that it should be divisible by 3.

If there exist multiple such numbers, your task is to print the smallest Kdigit number that can be created by using the digits that are available in the given set. In other words, you are required to determine the smallest Kdigit number that is divisible by 3 consisting of only the digits that are available in the set.

Note: The number should be a valid number and should not consist of any leading zeros unless the answer is 0 itself.

Input format

  • First line: N denoting the number of digits in the set
  • Next line: N space-separated digits in increasing order
  • Next line: K denoting the length of the required number

Output format

Print the largest possible Kdigit number that is divisible by 5. If it is not possible to print such a number, then print 1.

Constraints

1N100Digit91K105

Time Limit: 1
Memory Limit: 256
Source Limit:
Explanation

The smallest 2 digit number that is divisible by 3 consisting only of the digits (0,4,6,8) is 48.

Editor Image

?