Find the largest integer piece length x such that the scallions yield at least C pieces, then print the total leftover length.
Medium5Binary searchGreedyArrayMathInterviewNo attempts yetTime limit2sMemory limit256 MB
Seunggyun likes to cook, so he opened a chicken shop. The main dish is scallion chicken. Before opening, he stopped by the market and bought several scallions of uneven lengths.
To keep the taste the same across servings, Seunggyun puts a scallion piece of the same length into every serving. He believes more scallion tastes better, so he makes that length as large as he can. One serving takes exactly one piece, so pieces from different scallions are never combined into one serving.
The ruler in the shop has integer marks only, so a scallion is cut at integer lengths. A scallion of length L yields at most ⌊L/x⌋ pieces of length x, and the remaining Lmodx cannot be used as a piece.
Choose the largest integer length x that still allows all C ordered servings to be made, and print how much scallion is left over. The leftover is the total length of all scallions minus the C×x that went into the servings. Seunggyun puts that leftover into his ramen at the end of the day.
The first line contains the number of scallions S and the number of ordered servings C, separated by a space. (1≤S≤106, 1≤C≤106, S≤C)
Each of the next S lines contains the length L of one scallion as an integer. (1≤L≤109)
The total length of the scallions is at least C, so all ordered servings can always be made.
Print on one line the total length of scallion that Seunggyun puts into his ramen.
With scallions of length 440, 350, 230 and 5 ordered servings, the largest length per serving is 175. Two pieces come from 440, two from 350, and one from 230, which makes all 5 servings, and 90+0+55=145 is left over.