Divide Array Into Arrays With Max Difference — LeetCode 2966 Python Solution
- Problem
- #2966
- Pattern
- Greedy
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an integer array nums of size n where n is a multiple of 3 and a positive integer k. Divide the array nums into n / 3 arrays of size 3 satisfying the following condition: The difference between any two elements in one array is less than or equal to k.
Python solution
class Solution:
def divideArray(self, nums: List[int], k: int) -> List[List[int]]:
nums.sort()
ans = []
n = len(nums)
for i in range(0, n, 3):
t = nums[i : i + 3]
if t[2] - t[0] > k:
return []
ans.append(t)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Greedy
Take the locally best option every time — when you can prove that never costs you later. LeetCode 2966. Divide Array Into Arrays With Max Difference is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Greedy.
The greedy guide has the Python template for the pattern and the 346 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2966. Divide Array Into Arrays With Max Difference?
- LeetCode 2966. Divide Array Into Arrays With Max Difference is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2966. Divide Array Into Arrays With Max Difference?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2966. Divide Array Into Arrays With Max Difference?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2966. Divide Array Into Arrays With Max Difference cover?
- LeetCode 2966. Divide Array Into Arrays With Max Difference is tagged Greedy, Array and Sorting on LeetCode.