pythonalgorithmload-balancing

Optimizing solution for "Simple Load Balancing" problem on Codingame


Optimizing solution for "Simple Load Balancing" problem on Codingame

Description

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.

Initial Setup and Current Approach

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)

Current Approach

Additional Context

What I Tried and Expected

Approach:

Request for Guidance

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!


Solution

  • 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)