algorithm to find a number in which product of number of 4 & 7 is maximum in given range -
i stuck in question in lower bound l , upper bound u given.
suppose in decimal representation of integer x digit 4 appears a times , digit 7 appears b times.
problem find x has maximum value of a*b l<=x<=u.
there efficient algorithm solve it?
if understood problem correctly, following should work:
- assume numbers have same number of digits (if e.g. l has less digits u, can fill in beginning 0 s).
- let z = u - l.
- now go first (/highest/leftmost) digit last one. if looking @ i th digit, let l(i), u(i), z(i) , x(i) corresponding digit.
- for leading z(i) 0, set x(i) = l(i) (we don't have choice).
- for first not 0 z(i) check: there 4 or 7 in interval [l(i), u(i)-1]? if yes let x(i) 4 or 7 otherwise let x(i) = u(i)-1.
- now fill rest of x 4s , 7s such choose 4 if have assigned more 7s far , vice versa.
maybe example can in understanding this:
given u = 5000 , l = 4900.
now z = 0100.
from algorithm set
- x(1) = l(1) = 4 (we have no choice)
- x(2) = u(2)-1 = 9 (the first non 0 digit in z)
- x(3) = 7 (we had 4)
- x(4) = 4 (can chosen arbitrarily)
leading x = 4974 objective of 2*1=2
Comments
Post a Comment