Sponsored
Sponsored
This approach uses a stack to build the competitive subsequence. The basic idea is to iterate through the array and maintain a stack where the final size is k
. For each element, we decide whether it should be added to the stack or replace the top element of the stack, which ensures the stack remains a competitive sequence.
We will replace the top element of the stack if the current element is smaller and there are enough elements left to fill the required subsequence size.
This method ensures that the maintained sequence is minimal and competitive, based on the problem constraints.
Time Complexity: O(n)
where n
is the number of elements in nums
.
Space Complexity: O(k)
to store the competitive subsequence.
1#include <vector>
2#include <iostream>
3using namespace std;
4
5vector<int> mostCompetitive(vector<int>& nums, int k) {
6 vector<int> stack;
7 int to_remove = nums.size() - k; // number of optional removals
8 for (int num : nums) {
9 while (!stack.empty() && stack.back() > num && to_remove > 0) {
10 stack.pop_back();
11 to_remove--;
12 }
13 stack.push_back(num);
14 }
stack.resize(k);
return stack;
}
int main() {
vector<int> nums = {3, 5, 2, 6};
int k = 2;
vector<int> result = mostCompetitive(nums, k);
for (int num : result) cout << num << " ";
return 0;
}
The function mostCompetitive
uses a vector to simulate a stack and builds the most competitive subsequence by iteratively comparing elements. The variable to_remove
keeps track of how many elements can be removed to ensure the remaining subsequences size.
At every step, if the current element is smaller than the top of the stack and removals are still available, the top is popped to maintain the competitive property.
This approach builds upon the idea that maintaining a competitive subsequence can be achieved by iteratively reducing and replacing elements in a greedy fashion, focusing directly on modifications to an output array.
This strategy is slightly different from a pure stack-based approach as it directly handles result index placement while keeping track of candidates for subsequences and managing the required number of subsequence slots.
Time Complexity: O(n)
.
Space Complexity: O(k)
.
The approach uses an array result
to directly keep track of current selections. It employs a similar logic as before, but in terms of placement, directly filling array slots and managing index replacement based on element choices.
This provides direct insight into how the subsequence is filled.