-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathcount-fancy-numbers-in-a-range.py
More file actions
80 lines (73 loc) · 2.79 KB
/
count-fancy-numbers-in-a-range.py
File metadata and controls
80 lines (73 loc) · 2.79 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Time: O(dlogd + g + d^2 + g * d) = O(g * d + d^2), d = logr, g = len(good)
# Space: O(g + d)
# bfs, dp, principle of inclusion and exclusion
class Solution(object):
def countFancy(self, l, r):
"""
:type l: int
:type r: int
:rtype: int
"""
def count(x):
def length(n): # Time: O(logn)
result = 0
while n:
result += 1
n //= 10
return result
def total(n): # Time: O(logn)
result = 0
while n:
result += i%10
n //= 10
return result
def check(n): # Time: O(logn)
asc = desc = True
while n >= 10:
if not (n//10)%10 < n%10:
asc = False
if not (n//10)%10 > n%10:
desc = False
n //= 10
return asc or desc
def bfs(x): # Time: O(g), g = len(result)
result = [i for i in xrange(1, min(9, x)+1)]
for diff in (1, -1):
q = []
for i in xrange(1, min(9, x)+1):
q.append(i)
while q:
new_q = []
for u in q:
curr = u%10
d = curr+diff
while 0 <= d <= 9:
v = u*10+d
if v <= x:
new_q.append(v)
result.append(v)
d += diff
q = new_q
return result
def dp(x): # Time: O(d^2), d = logr
l = length(x)
mx = l*9
dp = [[0]*(mx+1) for _ in xrange(2)] # dp[tight][sum]
dp[1][0] = 1
base = 10**(l-1)
for i in xrange(l):
new_dp = [[0]*(mx+1) for _ in xrange(2)]
v = (x//base)%10
base //= 10
for t in xrange(2):
for s in xrange(mx+1):
if dp[t][s] == 0:
continue
for d in xrange((v if t == 1 else 9)+1):
new_dp[t == 1 and d == v][s+d] += dp[t][s]
dp = new_dp
return sum(dp[0][i]+dp[1][i] for i in xrange(mx+1) if lookup[i])
lookup = [check(i) for i in xrange(length(x)*9+1)]
good = bfs(x)
return len(good)+dp(x)-sum(lookup[total(x)] for x in good)
return count(r)-count(l-1)