95B - Lucky Numbers - CodeForces Solution


dp greedy *1800

Please click on ads to support us..

Python Code:

def nr47(a):
	n4 = a.count('4')
	n7 = a.count('7')
	pre = 0
	if n4 < n7:
		need = (n7 - n4) // 2
		i = 1
		k = 0
		while k < need + 1 or (a[-i]) == '7':
		    k += (a[-i] == '7')
		    i += 1
		a = a[:-i] + '7'
		a += '4' * (need + i - k)
		a += '7' * (k - need - 1)
	elif n4 > n7:
		need = (n4 - n7) // 2
		i = 1
		k = 0
		while k < need:
			k += a[-i] == '4'
			i += 1
		i -= 1
		a = a[:-i] + '7' * i
	return a
def n47(a):
    ret = ''
    g = len(a)
    i = 0
    for t in a:
        if int(t) < 4:
            ret += (g - i) * '4'
            break
        elif int(t) == 4:
            ret += '4'
            n4 = i
        elif int(t) < 7:
            ret += '7' + '4' * (g - i - 1)
            break
        elif int(t) == 7:
            ret += '7'
        else:
            ret = ret[:n4] + '7' + '4' * (g - n4 - 1)
            break
        i += 1
    return ret
def big(a):
	global k
	o = 1
	for t in a:
		if int(t) > 7 or (o > k // 2 and int(t) > 4):
			return True
		elif (int(t) < 7 and not (o > k // 2)) or (int(t) < 4 and (o > k // 2)):
			return False
		o += 1
	return False
a = input()
k = len(a)
if k % 2 == 1:
	print('4' * ((k + 1) // 2) + '7' * ((k + 1) // 2))
else:
	if big(a):
		print('4' * (k // 2 + 1) + '7' * (k // 2 + 1))
	else:
	    a = nr47(n47(a))
	    print(a)


Comments

Submit
0 Comments
More Questions

137. Single Number II
130. Surrounded Regions
129. Sum Root to Leaf Numbers
120. Triangle
102. Binary Tree Level Order Traversal
96. Unique Binary Search Trees
75. Sort Colors
74. Search a 2D Matrix
71. Simplify Path
62. Unique Paths
50. Pow(x, n)
43. Multiply Strings
34. Find First and Last Position of Element in Sorted Array
33. Search in Rotated Sorted Array
17. Letter Combinations of a Phone Number
5. Longest Palindromic Substring
3. Longest Substring Without Repeating Characters
1312. Minimum Insertion Steps to Make a String Palindrome
1092. Shortest Common Supersequence
1044. Longest Duplicate Substring
1032. Stream of Characters
987. Vertical Order Traversal of a Binary Tree
952. Largest Component Size by Common Factor
212. Word Search II
174. Dungeon Game
127. Word Ladder
123. Best Time to Buy and Sell Stock III
85. Maximal Rectangle
84. Largest Rectangle in Histogram
60. Permutation Sequence