I wrote the python program for this question based on the concept of binary search but my answer is getting tle I don’t know why any help will be appreciated.
from sys import stdin, stdout
t = int(stdin.readline())
def isValid(max_time, arr, parathas_needed):
time = 0
parathas_cooked = 0
cook_number = 0
count = 1
while True:
time += arr[cook_number] * count
parathas_cooked += 1
count += 1
if time > max_time:
parathas_cooked -= 1
cook_number += 1
time = 0
count = 1
if cook_number == len(arr):
return False
if parathas_cooked >= parathas_needed:
return True
return False
for _ in range(t):
parathas_needed = int(stdin.readline())
if parathas_needed == 0:
print(0)
continue
cook_ranks = [int(i) for i in stdin.readline().split()]
size = cook_ranks.pop(0)
# print(cook_ranks)
cook_ranks = sorted(cook_ranks)
s = 0
e = cook_ranks[-1] * (parathas_needed * (parathas_needed + 1) // 2)
# print(e)
res = 0
while s <= e:
mid = s + (e - s) // 2
# print(s, e, mid)
if isValid(mid, cook_ranks, parathas_needed):
res = mid
# print("res", res)
e = mid - 1
else:
s = mid + 1
print(res)