Skip to content

Commit bc7c5a0

Browse files
committed
feat: 2966
1 parent 9846f17 commit bc7c5a0

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# 2966. Divide Array Into Arrays With Max Difference
2+
3+
## Intuition
4+
5+
The main idea is to group the sorted array into subarrays of size 3, ensuring that the maximum difference within each group does not exceed k. Sorting helps to minimize the difference within each group.
6+
7+
## Approach
8+
9+
1. Sort the input array `nums` in ascending order.
10+
2. Iterate through the array in steps of 3, forming groups of three consecutive elements.
11+
3. For each group, check if the difference between the largest and smallest element is greater than `k`. If so, return an empty array as it's impossible to form such groups.
12+
4. If the group is valid, add it to the result.
13+
5. Return the list of valid groups.
14+
15+
## Complexity
16+
17+
- Time complexity: O(n log n)
18+
- Space complexity: O(n)
19+
20+
## Keywords
21+
22+
- Greedy
23+
- Grouping
24+
25+
## Code
26+
27+
```go
28+
func divideArray(nums []int, k int) [][]int {
29+
ret := make([][]int, 0)
30+
sort.Ints(nums)
31+
32+
for i := 0; i < len(nums); i += 3 {
33+
tmp := []int{nums[i]}
34+
if (i + 1 < len(nums) && nums[i + 1] - nums[i] > k) || (i + 2 < len(nums) && nums[i + 2] - nums[i] > k) {
35+
return [][]int{}
36+
}
37+
if i + 1 < len(nums) {
38+
tmp = append(tmp, nums[i + 1])
39+
}
40+
if i + 2 < len(nums) {
41+
tmp = append(tmp, nums[i + 2])
42+
}
43+
ret = append(ret, tmp)
44+
}
45+
return ret
46+
}
47+
```

docs/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@
8282
| 2444 | Count Subarrays With Fixed Bounds | [go](Hard/2444%20Count%20Subarrays%20With%20Fixed%20Bounds.md) | H |
8383
| 2742 | Paiting the Walls | [go](Hard/2742%20Painting%20the%20Walls.md) | H |
8484
| 2894 | Divisible and Non-divisible Sums Difference | [go](Easy/2894%20Divisible%20and%20Non-divisible%20Sums%20Difference.md) | E |
85+
| 2966 | Divide Array Into Arrays With Max Difference | [go](Medium/2966%20Divide%20Array%20Into%20Arrays%20With%20Max%20Difference.md) | M |
8586
| 3024 | Type of Triangle | [go](Easy/3024%20Type%20of%20Triangle.md) | E |
8687
| 3355 | Zero Array Transformation I | [go](Medium/3355%20Zero%20Array%20Transformation%20I.md) | M |
8788
| 3362 | Zero Array Transformation III | [go](Medium/3362%20Zero%20Array%20Transformation%20III.md) | M |

0 commit comments

Comments
 (0)