We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
My approach is of complexity O (kn), where k = range (min (array) to max (array)) (inclusive) and n = size of the array. It passed all the test cases.
REMEMBER: The point of convergence doesn't HAVE to be an element from the array. It can be any number in the range of min to max, so I applied exhaustive search.
def get_optimal (array, size, pivot, op1, op2):
inc = dec = cost = 0
for i in array:
if (i < pivot):
inc += (pivot - i);
elif (i > pivot):
dec += (i - pivot);
size, op1, op2 = [int (i) for i in input ().split ()];
array, optimal = [int (i) for i in input ().split ()], float ('inf');
for i in range (min (array), max (array) + 1):
temp = get_optimal (array, size, i, op1, op2);
optimal = temp if optimal > temp else optimal;
print (optimal);
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Beautiful Array
You are viewing a single comment's thread. Return to all comments →
My approach is of complexity O (kn), where k = range (min (array) to max (array)) (inclusive) and n = size of the array. It passed all the test cases.
REMEMBER: The point of convergence doesn't HAVE to be an element from the array. It can be any number in the range of min to max, so I applied exhaustive search.
def get_optimal (array, size, pivot, op1, op2):
inc = dec = cost = 0
for i in array:
if (i < pivot):
inc += (pivot - i);
elif (i > pivot):
dec += (i - pivot);
size, op1, op2 = [int (i) for i in input ().split ()];
array, optimal = [int (i) for i in input ().split ()], float ('inf');
for i in range (min (array), max (array) + 1):
temp = get_optimal (array, size, i, op1, op2);
optimal = temp if optimal > temp else optimal;
print (optimal);