FastPrepMinimum Servers for an Exact Load

Minimum Servers for an Exact Load

JP Morgan Chase logoJP Morgan Chase● MediumINTERNOA

Problem statement

You are given an array server of request-handling capacities and an integer expected_load. Every capacity is a power of two.

Choose the minimum number of servers whose capacities sum to exactly expected_load.

  • Each server may be selected at most once.
  • Different servers may have the same capacity.
  • The selected capacities must equal the load exactly; exceeding it is not allowed.

Return the minimum number of selected servers, or -1 if no selection is possible.

Function

getMinServers(expected_load: int, server: int[]) → int

Examples

Example 1

expected_load = 3server = [1,1,2,4]return = 2

Select the server of capacity 2 and either server of capacity 1. Their total capacity is 1 + 2 = 3. No single server has capacity 3, so two servers are necessary and sufficient.

Example 2

expected_load = 4server = [1,1,1]return = -1

All three servers together provide capacity 3, which is less than 4. No selection can meet the load.

Constraints

  • 1 <= server.length <= 10^5
  • 1 <= server[i] <= 10^9
  • Every capacity is a power of two.
  • 1 <= expected_load <= 10^9

More JP Morgan Chase problems

See JP Morgan Chase hiring insights
Saved
public int getMinServers(int expected_load, int[] server) {
    // Write your code here.
}
Checking account…