The standard approach would be to use a separate variable to keep track of the highest value seen, but there's an easier trick here. Since numbers generally increase in a roman numeral notation from right to left, any subtractive number must also be smaller than our current ans.
So we can avoid the need for an extra variable here. We do run into the case of repeated numerals causing an issue (ie, "III"), but we can clear that by multiplying num by any number between 2 and 4 before comparing it to ans, since the numerals jump in value by increments of at least 5x.
Because that's not a valid Roman numeral sequence. Roman numbers are written in descending value order, with the exception for 9s and 4s and their equivalents in orders of magnitude.
At the start, the "CM" would be read as 900, because "C" is 100 and "M" is 1000. But then you have a "D", which would be another 500, so "CMD" would be 1400. But you'd never write it that way instead of "MCD" which is 1000+400 (rather than 900+500).
Then you have another "M", which is another 1000, but then that "M" should go at the beginning.
So assuming that the "CM" is supposed to be 900 (rather than 1100), then this should be written as "MMCD", or 1000+1000+400 (M+M+CD).
what do you mean by "with the exception for 9s and 4s and their equivalents in orders of magnitude." I don't understand the "s" meaning and why "9s" and "4s". Sorry, if you have time can you explain to me.
This part of the explanation covers the 4:
Thank you so much, i got it cleared :)
why is it wrong when I put the test case with roman number :"CMDM"
Because that's not a valid Roman numeral sequence. Roman numbers are written in descending value order, with the exception for 9s and 4s and their equivalents in orders of magnitude.
At the start, the "CM" would be read as 900, because "C" is 100 and "M" is 1000. But then you have a "D", which would be another 500, so "CMD" would be 1400. But you'd never write it that way instead of "MCD" which is 1000+400 (rather than 900+500).
Then you have another "M", which is another 1000, but then that "M" should go at the beginning.
So assuming that the "CM" is supposed to be 900 (rather than 1100), then this should be written as "MMCD", or 1000+1000+400 (M+M+CD).
what do you mean by "with the exception for 9s and 4s and their equivalents in orders of magnitude." I don't understand the "s" meaning and why "9s" and "4s". Sorry, if you have time can you explain to me.
you could check the dev.to/seanpgallivan/solution-inte...