 Open in App
Not now

# C Program to Maximize Time by Replacing ‘_’ in a Given 24-Hour Format Time

• Last Updated : 26 Oct, 2022

Given a string S representing a time in 24 hours format, with ‘_’ placed at positions of some digits, the task is to find the maximum time possible by replacing the characters ‘_’ with any digit.

Examples:

Input: S = “0_:4_”
Output: 09:39
Explanation: Replacing the characters S and S with ‘9’ modifies the string to “09:49”, which is the maximum time possible.

Input: S = “__:__”
Output: 23:59

Approach: The given problem can be solved by greedily selecting the digits for each ‘_’ present in the string. Follow the steps below to solve the problem:

• If the character S is equal to ‘_’ and S is either ‘_’ or is less than 4, then assign ‘2‘ to S. Otherwise, assign ‘1’ to S.
• If the character S is equal to ‘_’ and S is ‘2’, then assign ‘3’ to S. Otherwise, assign ‘9‘ to S.
• If the character S is equal to ‘_’, then assign ‘5’ to S.
• If the character S is equal to ‘_’, then assign ‘9‘ to S.
• After completing the above steps, print the modified string S.

Below is the implementation of the above approach:

## C

 `// C program for above approach``#include ``#include `` ` `// Function to find the maximum``// time possible by replacing``// each '_' with any digit``char``* maximumTime(``char` `s[])``{``    ``// If the first character is '_'``    ``if` `(s == ``'_'``) {`` ` `        ``// If s is '_' or``        ``// s is less than 4``        ``if` `((s == ``'_'``) || (s >= ``'0'` `&& s < ``'4'``)) {`` ` `            ``// Update s as 2``            ``s = ``'2'``;``        ``}``        ``else` `{ ``// Otherwise, update s = 1``            ``s = ``'1'``;``        ``}``    ``}`` ` `    ``// If s is equal to '_'``    ``if` `(s == ``'_'``) {`` ` `        ``// If s is equal to '2'``        ``if` `(s == ``'2'``) {``            ``s = ``'3'``;``        ``}``      ``// otherwise``        ``else` `{ ``            ``s = ``'9'``;``        ``}``    ``}`` ` `    ``// If S is equal to '_'`` ` `    ``if` `(s == ``'_'``) {`` ` `        ``s = ``'5'``;``    ``}`` ` `    ``// If s is equal to '_'`` ` `    ``if` `(s == ``'_'``) {`` ` `        ``s = ``'9'``;``    ``}`` ` `    ``return` `s; ``// Return the modified string``}``int` `main()``{``    ``char` `S[] = ``"0_:4_"``;``    ``printf``(``"%s"``, maximumTime(S));``    ``return` `0;``}`` ` `// This code is contributed by Tapesh (tapeshdua420)`

Output

`09:49`

Time Complexity: O(1)
Auxiliary Space: O(1)

Please refer complete article on Maximize time by replacing ‘_’ in a given 24 Hour format time for more details!

My Personal Notes arrow_drop_up