I'm currently tackling the "Simple Load Balancing" problem on Codingame, where the objective is to distribute k
jobs among N
servers to minimize the difference between the maximum and minimum loads.
import sys
import math
# Auto-generated code below aims at helping you parse
# the standard input according to the problem statement.
n = int(input()) # Number of servers
k = int(input()) # Number of jobs to distribute
# Read initial loads of servers
arr = []
for i in input().split():
arr.append(int(i))
def load_diff(n, k, arr):
arr.sort()
while k > 0:
arr[0] += 1
k -= 1
arr.sort()
return arr[-1] - arr[0]
result = load_diff(n, k, arr)
print(result)
arr
list after each job distribution to maintain order, ensuring the smallest server load is adjusted first.k
times, incrementing the load of the server with the minimum load to distribute jobs.Performance Issue: When running all test cases, all pass except for test case 4, where I encounter a timeout (Le délai d'exécution du processus a été dépassé
). This suggests that my solution may not be optimized enough to handle larger inputs or specific edge cases efficiently.
Challenge Link: Simple Load Balancing on Codingame
arr
list after each job distribution to maintain order, ensuring the smallest server load is adjusted first. I then iterated k
times, incrementing the load of the server with the minimum load to distribute jobs.Le délai d'exécution du processus a été dépassé
), indicating that my solution may not be optimized enough for larger inputs or specific edge cases.This problem is part of a coding challenge on Codingame, and I'm seeking advice on improving my solution's performance and effectiveness.
Any suggestions or help!
We want to make the minimum element in the array (of number of jobs on each server) as large as possible in order to minimize the difference between the maximum and minimum element. To do this efficiently, we can binary search for the largest value x
such that we can increase all elements in the array less than x
to be equal to x
using no more than k
jobs. If we can increase all elements to the maximum value and there are still jobs remaining to distribute, the answer is either 0
or 1
, depending on whether the remaining jobs can be evenly distributed into n
servers.
def load_diff(n, k, arr):
low = min(arr)
high = max(arr)
while low <= high:
mid = low + high >> 1
if sum(max(0, mid - x) for x in arr) > k:
high = mid - 1
else:
low = mid + 1
if high < max(arr):
return max(arr) - high
return min(1, (k - (n * max(arr) - sum(arr))) % n)