Find Subsequence of Length K With the Largest Sum

Sanjeev SharmaSanjeev Sharma
1 min read

Advertisement

Problem

Find a subsequence of length k (preserving order) with the largest possible sum.

Key insight: Select k indices with largest values. Sort by value to pick top k, then sort selected indices by position.

Solutions

# Python
import heapq

def maxSubsequence(nums, k):
    # Get k largest values' indices
    heap = heapq.nlargest(k, enumerate(nums), key=lambda x: x[1])
    heap.sort()  # sort by index to preserve order
    return [nums[i] for i, _ in heap]
// C++
vector<int> maxSubsequence(vector<int>& nums, int k) {
    vector<pair<int,int>>iv(nums.size());
    for(int i=0;i<(int)nums.size();i++)iv[i]={nums[i],i};
    partial_sort(iv.begin(),iv.begin()+k,iv.end(),[](auto&a,auto&b){return a.first>b.first;});
    sort(iv.begin(),iv.begin()+k,[](auto&a,auto&b){return a.second<b.second;});
    vector<int>res; for(int i=0;i<k;i++)res.push_back(iv[i].first);
    return res;
}
// Java
public int[] maxSubsequence(int[] nums, int k) {
    Integer[]idx=new Integer[nums.length]; for(int i=0;i<nums.length;i++)idx[i]=i;
    Arrays.sort(idx,(a,b)->nums[b]-nums[a]);
    Integer[]top=Arrays.copyOf(idx,k);
    Arrays.sort(top);
    int[]res=new int[k]; for(int i=0;i<k;i++)res[i]=nums[top[i]];
    return res;
}
// JavaScript
function maxSubsequence(nums, k) {
    const idx = [...nums.keys()].sort((a,b)=>nums[b]-nums[a]).slice(0,k).sort((a,b)=>a-b);
    return idx.map(i=>nums[i]);
}

Complexity

  • Time: O(n log k), Space: O(k)

Advertisement

Sanjeev Sharma

Written by

Sanjeev Sharma

Full Stack Engineer · E-mopro