[LeetCode] Widest Possible Fence

4007. Widest Possible Fence

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

class Solution {
public:
int maximumWidth(vector<int>& planks) {
map<int,int> freq;
for(auto& p : planks) freq[p]++;
unordered_map<int,int> ffreq;
for(auto it = begin(freq); it != end(freq); it++) {
ffreq[it->first] += it->second;
ffreq[it->first * 2] += it->second / 2;
for(auto jt = next(it); jt != end(freq); jt++) {
ffreq[it->first + jt->first] += min(it->second, jt->second);
}
}
int res = 0;
for(auto& [k,v] : ffreq) res = max(res, v);
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2026/09/03/PS/LeetCode/widest-possible-fence/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.