Leetcode 1403. Minimum Subsequence in Non
Given an array nums
of integers, you need to return the minimum subsequence such that the sum of the subsequence is strictly greater than the sum of the remaining elements of the array. If there are multiple solutions, return the subsequence with the maximum sum. If there still are multiple solutions, return the subsequence with the minimum size. It can be assumed that there is always a solution.
#include <iostream>
#include <vector>
#include <algorithm>
std::vector<int> minSubsequence(std::vector<int>& nums) {
// Calculate total sum of the array
int totalSum = 0;
for (int num : nums) {
totalSum += num;
}
// Sort the array in non-increasing order
std::sort(nums.begin(), nums.end(), std::greater<int>());
// Select elements until their sum is greater than half of totalSum
std::vector<int> result;
int subsequenceSum = 0;
for (int num : nums) {
subsequenceSum += num;
result.push_back(num);
if (subsequenceSum > totalSum / 2) {
break;
}
}
return result;
}
int main() {
std::vector<int> nums = {4, 3, 10, 9, 8};
std::vector<int> result = minSubsequence(nums);
std::cout << "Minimum Subsequence: ";
for (int num : result) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
nums
.The overall time complexity is dominated by the sorting step, so the final time complexity is O(n log n).
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?