Leetcode 2099. Find Subsequence of Length K With the Largest Sum
Given an integer array nums
and an integer k
, return the subsequence of length k
that has the largest sum. If there are multiple subsequences, return the one with the largest sum and smallest lexicographical order.
nums
contain negative numbers?
nums
.k
and the length of nums
?
k
always exists?
k
largest elements in the array.k
largest elements, traverse the array and select them in order as they appear.import java.util.*;
public class Solution {
public int[] maxSubsequence(int[] nums, int k) {
int n = nums.length;
// Step 1: Create an array of index and values from nums
int[][] numWithIndex = new int[n][2];
for (int i = 0; i < n; i++) {
numWithIndex[i][0] = nums[i];
numWithIndex[i][1] = i;
}
// Step 2: Sort the array based on values in descending order
Arrays.sort(numWithIndex, (a, b) -> b[0] - a[0]);
// Step 3: Collect the indices of the top k elements
int[] indices = new int[k];
for (int i = 0; i < k; i++) {
indices[i] = numWithIndex[i][1];
}
// Step 4: Sort the indices to maintain the order of appearance
Arrays.sort(indices);
// Step 5: Construct the result based on sorted indices
int[] result = new int[k];
for (int i = 0; i < k; i++) {
result[i] = nums[indices[i]];
}
return result;
}
public static void main(String[] args) {
Solution sol = new Solution();
int[] nums = {3, 4, 3, 3};
int k = 2;
int[] result = sol.maxSubsequence(nums, k);
System.out.println(Arrays.toString(result)); // Output: [4, 3]
}
}
nums
.k
numbers.k
elements.Thus, the time complexity for the entire solution is O(n log n), considering k
is relatively small compared to 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?