Tiktok Intern OA
Anonymous User
508

Couldn't managed to solve it. Is it 2 ptr approach?

def maximumProductSum(memory):
n = len(memory)
mod = 10**9 + 7

total_efficiency = sum((i + 1) * x for i, x in enumerate(memory))
result = total_efficiency

idx = 1
while idx <= n // 2:
    to_swap = sorted(range(idx), key=lambda i: memory[i] - memory[n - i - 1])
    current_efficiency = total_efficiency

    swap_count = 0  # Keep track of how many swaps were done for this index
    for i in to_swap:
        if swap_count > 0:
            break  # Skip if this server has already been involved in a swap

        current_efficiency += (memory[n - i - 1] - memory[i]) * (idx - i) * 2
        swap_count += 1

    result = max(result, current_efficiency)
    idx += swap_count  # Move to the next index

return result % mod

image
image

Comments (2)