Leetcode 3069. Distribute Elements Into Two Arrays I
Given an array nums
and an integer k
, your task is to distribute the nums
array’s elements into two arrays a
and b
such that:
k
elements.a
and the elements of b
.nums
nums
negative, non-negative, or can they be both?nums
array length is less than 2k
, how should we handle it? (assuming input constraint)a
and b
, or just the maximum sum of absolute differences?nums
?nums
and k
?Assuming that elements can be positive or negative, the size of nums
is guaranteed to be at least 2k
, and we need to return exactly two arrays a
and b
.
nums
array in descending order to simplify the selection of the largest differences.a
and b
:
k
largest elements in one array (a
) and the next k
largest elements in another array (b
). This will maximize the differences because we are pairing large numbers against the next set of smaller numbers.a
and b
, iterate through both arrays and sum the absolute differences.Here’s a C++ implementation based on the above strategy:
#include <iostream>
#include <vector>
#include <algorithm>
std::pair<std::vector<int>, std::vector<int>> distributeElements(std::vector<int>& nums, int k) {
// Sort the array in descending order
std::sort(nums.begin(), nums.end(), std::greater<int>());
std::vector<int> a(nums.begin(), nums.begin() + k);
std::vector<int> b(nums.begin() + k, nums.begin() + 2 * k);
return {a, b};
}
int main() {
std::vector<int> nums = {1, 3, 2, 2, 5, 2, 7, 8, 1, 9, 10, 6};
int k = 3;
auto result = distributeElements(nums, k);
std::vector<int> a = result.first;
std::vector<int> b = result.second;
std::cout << "Array a: ";
for (const auto& num : a) {
std::cout << num << " ";
}
std::cout << "\nArray b: ";
for (const auto& num : b) {
std::cout << num << " ";
}
return 0;
}
The time complexity for sorting the array is (O(n \log n)), where (n) is the size of the nums
array. The selection of elements takes linear time, i.e., (O(n)). Hence, the overall time complexity is dominated by the sorting step, making it (O(n \log n)).
The space complexity is (O(1)) additional space if not counting the storage for the arrays a
and b
, making it essentially (O(n)) accounting for the inputs and outputs together.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?