To solve this problem, we need to determine the minimum number of operations required to make a given number (represented as a string) divisible by 25. The key insight here is that any number divisible by 25 must end in one of the following pairs: "00", "25", "50", or "75". Additionally, the number zero itself is divisible by 25, so we need to handle this case separately.
def minimal_operations(s):
n = len(s)
max_len = 0
targets = ["00", "25", "50", "75"]
for t in targets:
first, second = t[0], t[1]
# Find the rightmost occurrence of the second character in the target pair
idx_second = s.rfind(second)
if idx_second == -1:
continue
# Find the rightmost occurrence of the first character before idx_second
idx_first = s.rfind(first, 0, idx_second)
if idx_first == -1:
continue
# Length of the subsequence is (digits up to idx_first) + 1 (second character)
current_length = idx_first + 2
if current_length > max_len:
max_len = current_length
# Check if there is any zero (valid as a single digit)
if '0' in s:
max_len = max(max_len, 1)
if max_len == 0:
return -1
return n - max_len
This approach efficiently finds the solution by leveraging the properties of numbers divisible by 25 and ensures we handle all edge cases (like zero) correctly. The time complexity is O(n) for each target pair, which is O(4n) = O(n) overall, making it optimal for large input sizes.
Answer: The code provided above is the solution to the problem. For a given input string s, it returns the minimal number of operations to make the number divisible by 25, or -1 if it's impossible. The final answer is the function minimal_operations as written.
(免責(zé)聲明:本文為本網(wǎng)站出于傳播商業(yè)信息之目的進(jìn)行轉(zhuǎn)載發(fā)布,不代表本網(wǎng)站的觀點及立場。本文所涉文、圖、音視頻等資料的一切權(quán)利和法律責(zé)任歸材料提供方所有和承擔(dān)。本網(wǎng)站對此資訊文字、圖片等所有信息的真實性不作任何保證或承諾,亦不構(gòu)成任何購買、投資等建議,據(jù)此操作者風(fēng)險自擔(dān)。) 本文為轉(zhuǎn)載內(nèi)容,授權(quán)事宜請聯(lián)系原著作權(quán)人,如有侵權(quán),請聯(lián)系本網(wǎng)進(jìn)行刪除。