Widest Possible Fence Problem
Description
LeetCode Problem 4007.
You are given an integer array planks, where planks[i] represents the height of the i^th wooden plank. Each plank has a width of 1 unit.
You want to build a fence consisting of planks that all have the same height.
You may either use a plank as is, or combine exactly two distinct original planks into a single plank whose height equals the sum of their heights. Each original plank can be used at most once, and not all original planks need to be used.
Return the maximum possible width of the fence that can be built.
Example 1:
Input: planks = [1,3,2,5,7,5,4,2,1]
Output: 4
Explanation:
We can have four planks of height 5.
- planks[3] = 5
- planks[5] = 5
- planks[0] + planks[6] = 1 + 4 = 5
- planks[1] + planks[2] = 3 + 2 = 5
Hence, the maximum width is 4.
Example 2:
Input: planks = [2,3,7]
Output: 1
Explanation:
- It is impossible to form two planks of the same height, even after combining two distinct original planks.
- Since not all original planks need to be used, we can choose any one plank as the fence.
- Therefore, the maximum possible width is 1.
Constraints:
1 <= planks.length <= 10001 <= planks[i] <= 10^9
Solution
Approach: Counting + Enumeration
First count how many planks have each height in a hash table cnt.
For a target height h, the planks of that height we can get come from three disjoint sources:
- planks that already have height
h:cnt[h]; - if
his even, pairs of two planks of heighth / 2:cnt[h / 2] / 2(rounded down); - for each pair of different heights
x < ywithx + y = h:min(cnt[x], cnt[y]).
For one fixed h these sources never share an original plank, so they can simply be added.
Iterate over each distinct height x and accumulate into a second table t:
t[x] += cnt[x];t[2x] += cnt[x] / 2(rounded down);- for each height
y > x,t[x + y] += min(cnt[x], cnt[y]).
The answer is the largest value in t.
Complexity: time O(n + m^2), space O(m^2) in the worst case for t, where n is the number of planks and m <= n the number of distinct heights.
from collections import Counter, defaultdict
class Solution:
def maximumWidth(self, planks: List[int]) -> int:
cnt = Counter(planks)
ans = 0
t = defaultdict(int)
for x, v1 in cnt.items():
t[x] += v1
t[x * 2] += v1 // 2
for y, v2 in cnt.items():
if y > x:
t[x + y] += min(v1, v2)
return max(t.values())