You are given an integer array planks, where planks[i] represents the height of the ith 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] = 5planks[5] = 5planks[0] + planks[6] = 1 + 4 = 5planks[1] + planks[2] = 3 + 2 = 5Hence, the maximum width is 4.
Example 2:
Input: planks = [2,3,7]
Output: 1
Explanation:
Constraints:
1 <= planks.length <= 10001 <= planks[i] <= 109Problem Overview: Given a set of fence posts, determine the maximum width of a fence that can be built without any gaps between posts.
Approach 1: Brute Force (O(n^2))
Check all possible pairs of fence posts to find the maximum width. For each pair, verify if all intermediate posts exist. This requires nested loops and results in quadratic time complexity.
Approach 2: Sorting and Greedy (O(n log n))
Sort the fence posts first. Then iterate through the sorted list, keeping track of the maximum gap between consecutive posts. The key insight is that sorting allows you to check adjacent posts efficiently, reducing the problem to a linear scan after sorting.
Recommended for interviews: The optimal approach is sorting followed by a greedy scan. Interviewers expect this solution as it demonstrates both algorithmic thinking and efficiency. Brute force shows basic understanding but lacks optimization.
Solutions for this problem are being prepared.
Try solving it yourself| Approach | Time | Space | When to Use |
|---|---|---|---|
| Brute Force | O(n^2) | O(1) | When input size is very small |
| Sorting and Greedy | O(n log n) | O(1) | General case, optimal solution |
Leetcode 4007 | Widest Possible Fence | Greedy | Leetcode biweekly contest 188 • CodeWithMeGuys • 259 views views
Watch 1 more video solutions →Practice Widest Possible Fence with our built-in code editor and test cases.
Practice on FleetCodePractice this problem
Open in Editor