Paths Subjects Questions Quizzes Pricing Search
Intermediate Open Pro

Cutting Wood

A sawmill has logs, an array where logs[i] is the length of the i-th log. The mill sets a single saw height h and cuts through every log at that height: any part of a log above height h is collected as usable wood (max(logs[i] - h, 0) from each log), and the parts at or below h are discarded as scrap.

Given logs and an integer target (the minimum total amount of wood the mill needs to collect), return the maximum integer saw height h such that the total wood collected across all logs is still >= target. It is guaranteed that h = 0 always satisfies the target (cutting at the ground always yields enough wood).

Example 1

Input: logs = [4, 9, 6, 2], target = 6
Output: 4
Explanation: At h = 5: 0 + 4 + 1 + 0 = 5 wood -- not enough.
At h = 4: 0 + 5 + 2 + 0 = 7 wood -- enough. Since h = 4 satisfies
the target and h = 5 does not, the maximum valid height is 4.

Example 2

Input: logs = [10, 10, 10], target = 15
Output: 5
Explanation: At h = 5, each log yields 5, for a total of 15 >= 15.
At h = 6, each log yields 4, for a total of 12 < 15. So 5 is the
largest height that still works.

Constraints

  • 1 <= logs.length <= 10^4
  • 1 <= logs[i] <= 10^9
  • 0 <= target <= sum(logs)

Share this question

← Back to Binary Search practice

We use cookies for product analytics to improve OmniAtlas. See our Privacy Policy.