Sobes.tech
Middle+

In the prototype of the ad sales network, the sale of ad spaces is organized as follows: buyers specify their price in advance, and for each ad space, they respond whether they are willing to buy it or not. It is necessary to implement a function that, before selling an ad space, waits for approval or rejection from buyers with high bid prices, and then sells the ad space to the buyer with the highest bid among those who agreed to buy. The function should return the index of the buyer as quickly as possible.

sobes.tech AI

Answer from AI

Your task is to identify the buyer with the highest price who agrees to purchase the ad space as quickly as possible. Buyer responses arrive asynchronously and can be in any order.

The main idea of the solution:

  1. Sort buyers by price in descending order — from the most expensive to the cheapest.
  2. Launch all accepts() promises in parallel.
  3. Process responses in order of decreasing price, so that as soon as the most expensive buyer agrees, you immediately return their index.
  4. If the most expensive declines, wait for the response from the next most expensive, and so on.

This approach allows you not to wait for all responses, but to return the result as early as possible.

Example implementation:

async function bestBuyer(buyers) {
  // Sort by descending price
  const sorted = buyers
    .map((buyer, index) => ({ buyer, index }))
    .sort((a, b) => b.buyer.price - a.buyer.price);

  // Launch all promises in parallel
  const acceptPromises = sorted.map(({ buyer }) => buyer.accepts());

  for (let i = 0; i < sorted.length; i++) {
    const accepted = await acceptPromises[i];
    if (accepted) {
      // Return the index of the buyer with the highest price who agreed
      return sorted[i].index;
    }
  }

  // If no one agreed
  return -1;
}

Thus, we do not wait for responses from buyers with lower prices if we have already received consent from a more expensive buyer. This speeds up obtaining the result.