Skip to content

Instantly share code, notes, and snippets.

@tatsuyax25
Created June 28, 2025 16:08
Show Gist options
  • Save tatsuyax25/b5766d44fe02aee3289b462ed79245ce to your computer and use it in GitHub Desktop.
Save tatsuyax25/b5766d44fe02aee3289b462ed79245ce to your computer and use it in GitHub Desktop.
You are given an integer array nums and an integer k. You want to find a subsequence of nums of length k that has the largest sum. Return any such subsequence as an integer array of length k. A subsequence is an array that can be derived from anoth
/**
* @param {number[]} nums
* @param {number} k
* @return {number[]}
*/
var maxSubsequence = function(nums, k) {
// Step 1: Map each element to a pair [value, originalIndex]
const withIndices = nums.map((num, index) => [num, index]);
// Step 2: Sort by value in descending order to find the top-k values
withIndices.sort((a, b) => b[0] - a[0]);
// Step 3: Take the top-k pairs
const topK = withIndices.slice(0, k);
// Step 4: Sort the selected pairs by original index to preserve subsequence order
topK.sort((a, b) => a[1] - b[1]);
// Step 5: Extract and return only the values
return topK.map(pair => pair[0]);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment