text: Minimum time required to print given string from a circular container based on given conditions | C ++ implementation for the above approach ; Function to calculate minimum time to print all characters in the string ; Current element where the pointer is pointing ; Find index of that element ; Calculate absolute difference between pointer index and character index as clockwise distance ; Subtract clockwise time from 26 to get anti - clockwise time ; Add minimum of both times to the answer ; Add one unit time to print the character ; Print the final answer ; Driver code ; Given string word ; Function call
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; void minTime ( string word ) { int ans = 0 ; int curr = 0 ; for ( int i = 0 ; i < word . length ( ) ; i ++ ) { int k = word [ i ] - ' a ' ; int a = abs ( curr - k ) ; int b = 26 - abs ( curr - k ) ; ans += min ( a , b ) ; ans ++ ; curr = word [ i ] - ' a ' ; } cout << ans ; } int main ( ) { string str = " zjpc " ; minTime ( str ) ; return 0 ; }