Electronic Lock
InterviewTime limit2sMemory limit1024 MB
Find the largest integer without leading zeros that uses exactly n lit segments, with digits drawn only from the given set.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Greedy
- Solved
- No attempts yet
Statement
Kowalski decided to build an electronic lock for his new invention. The lock is a sequence of 7-segment displays. There is no full keypad, so only some digits can be used in the password. The password is an integer without leading zeros.
Kowalski cannot read, but he can count. He wants exactly segments to light up when the password is entered. A segment is one of the unit line segments that make up a 7-segment display. Among all passwords that fit, he wants the largest one.

Fig. 1: How each digit is shown on a 7-segment display.
Help Kowalski find the number. At least one valid password is guaranteed to exist.
Input
The first line contains two integers and , where is the required number of lit segments and is the number of available digits (, ). The second line contains the available digits in increasing order.
Output
Print one number, the required password. It must not have leading zeros. At least one valid password is guaranteed to exist.
Hint
In the first example, exactly 7 segments must light up, so Kowalski must use 8 as the password.