FastPrepMinimum Full Glasses for an Exact Water Volume

Minimum Full Glasses for an Exact Water Volume

Marshall Wace logoMarshall Wace● MediumNEW GRADPHONE SCREEN

Problem statement

There is exactly one glass of each integer capacity from 1 through N litres.

You want to hold exactly K litres of water. Each glass must be either completely full or empty; partial filling is not allowed.

Return the minimum number of full glasses needed, or -1 if the target volume is impossible. If K = 0, return 0.

Function

solution(N: int, K: long) → int

Examples

Example 1

N = 5K = 8return = 2

Fill the glasses of capacities 5 and 3. One glass cannot hold 8 litres because the largest capacity is 5.

Example 2

N = 3K = 7return = -1

All three glasses together hold only 1 + 2 + 3 = 6 litres.

Example 3

N = 3K = 6return = 3

Every glass must be full to reach the total capacity of 6.

Example 4

N = 7K = 0return = 0

Leave every glass empty.

Constraints

  • 1 <= N <= 10^9.
  • 0 <= K <= 10^18.
  • Each capacity is available exactly once.

More Marshall Wace problems

See Marshall Wace hiring insights
Saved
public int solution(int N, long K) {
    // Write your solution here.
}
N5
K8
expected2
Checking account…