text: Minimize the total number of teddies to be distributed | Python implementation of the above approach ; Initializing one tablet for each student ; if left adjacent is having higher marks review and change all the dp values assigned before until assigned dp values are found wrong according to given constrains ; if right adjacent is having higher marks add one in dp of left adjacent and assign to right one ; n number of students ; marks of students ; solution of problem
code: def fun ( marks , n ) : NEW_LINE INDENT dp = [ 1 for i in range ( 0 , n ) ] NEW_LINE for i in range ( 0 , n - 1 ) : NEW_LINE INDENT if marks [ i ] > marks [ i + 1 ] : NEW_LINE INDENT temp = i NEW_LINE while True : NEW_LINE INDENT if marks [ temp ] > marks [ temp + 1 ] and temp >= 0 : NEW_LINE INDENT if dp [ temp ] > dp [ temp + 1 ] : NEW_LINE INDENT temp -= 1 NEW_LINE continue NEW_LINE DEDENT else : NEW_LINE INDENT dp [ temp ] = dp [ temp + 1 ] + 1 NEW_LINE temp -= 1 NEW_LINE DEDENT DEDENT else : NEW_LINE INDENT break NEW_LINE DEDENT DEDENT DEDENT elif marks [ i ] < marks [ i + 1 ] : NEW_LINE INDENT dp [ i + 1 ] = dp [ i ] + 1 NEW_LINE DEDENT DEDENT return ( sum ( dp ) ) NEW_LINE DEDENT n = 6 NEW_LINE marks = [ 1 , 4 , 5 , 2 , 2 , 1 ] NEW_LINE print ( fun ( marks , n ) ) NEW_LINE