IVXLCDM
InterviewTime limit1sMemory limit128 MB
Given a lowercase inscription line, find the largest value of a valid Roman numeral readable as a subsequence of its letters, or 0 if none.
- Level
Medium7 of 10
- Topics
- Greedy, String, Dynamic programming, Implementation
- Solved
- No attempts yet
Problem
Roman numerals are written with the seven letters I, V, X, L, C, D, and M, which stand for the values , , , , , , and respectively. A number is written by placing these letters (repeated when necessary) from the largest value on the left to the smallest on the right. For example, is written III and is written LXXIII.
The exceptions are values whose units digit is or , whose tens digit is or , and whose hundreds digit is or . These use the subtractive forms IV (), IX (), XL (), XC (), CD (), and CM (). For instance, , , , , and are written XXIV, XXXIX, XLIV, XLIX, and XCIV.
The following rules make every value have a unique representation:
- At most three consecutive
I,X, orCmay appear. - Each of
V,L, andDmay appear at most once. - Any number of
Mmay appear. - No other subtractive combinations are allowed (for example,
ICfor is forbidden).
In the Middle Ages the year a building was founded was often hidden in an inscription: some of its letters were emphasized, and reading only the emphasized letters in order spelled the year as a Roman numeral. For example, the inscription Matfyz is the best schooL In prague encodes MLI, that is, .
Over time an inscription may be damaged, so it is no longer known which letters were emphasized. Given only the plain text of an inscription, determine the latest year the building could have been founded — that is, the largest value of a valid Roman numeral that can be read as a subsequence of the inscription's letters (letter case is ignored). For example, from matfyz is the best school in prague one can read MCLI, that is, .
Input
The input consists of one or more nonempty lines . Each line contains only lowercase letters and spaces and has length at most characters. Read until the end of input.
Output
For each line , output a single line containing one integer: the largest value of a Roman numeral that can be encoded in by emphasizing some of its letters, or if no Roman numeral can be encoded.