Minimum time required to print given string from a circular container based on given conditions | Java 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
class GFG { static void minTime ( String word ) { int ans = 0 ; int curr = 0 ; for ( int i = 0 ; i < word . length ( ) ; i ++ ) { int k = ( int ) word . charAt ( i ) - 97 ; int a = Math . abs ( curr - k ) ; int b = 26 - Math . abs ( curr - k ) ; ans += Math . min ( a , b ) ; ans ++ ; curr = ( int ) word . charAt ( i ) - 97 ; } System . out . print ( ans ) ; } public static void main ( String [ ] args ) { String str = " zjpc " ; minTime ( str ) ; } }