↓Skip to main content
  1. LeetCode/

LeetCode 2099: Find Subsequence of Length K With the Largest Sum

·1 min· ·
LeetCode Easy Array Hash-Table Sorting Heap-Priority-Queue
Wei Yi Chung
Author
Wei Yi Chung
Working at the contributing of open source, distributed systems, and data engineering.
Table of Contents

Meta Data
#

Difficulty: easy First Attempt: 2022-11-22

  • Submissions: Accepted → Runtime Error → Accepted

Approach
#

A subsequence keeps the original order, while the largest sum comes from the k largest values. Take the top k of (value, index) by value (sorting or a size-k heap, Heap Template 1), then output them sorted by index.

My Attempts
#

In 2022 it passed at once by popping the n - k smallest from a heap and sorting by index. A 2025 rewrite wrote sort(lambda x: -x[1]); the key must be passed by keyword (TypeError), and adding key= passed.

Solution
#

class Solution:
    def maxSubsequence(self, nums: List[int], k: int) -> List[int]:
        top = heapq.nlargest(k, range(len(nums)), key=lambda i: nums[i])
        return [nums[i] for i in sorted(top)]

Complexity
#

Time O(n log k), space O(k).

Mistakes to Avoid
#

  • Restore the original order by sorting the chosen indices.
  • Pass the sort key as a keyword argument: sort(key=...).

Interview Explanation
#

The largest sum uses the k largest values, but order must be preserved, so I pick k indices by value with nlargest and output their values in index order. Time O(n log k).

Related

LeetCode 2335: Minimum Amount of Time to Fill Cups
·1 min
LeetCode Easy Array Greedy Sorting Heap-Priority-Queue
LeetCode 2335 note: the answer is max(the largest count, ceil(total / 2)); simulating means filling one cup from each of the two largest every second
LeetCode 1464: Maximum Product of Two Elements in an Array
·1 min
LeetCode Easy Array Sorting Heap-Priority-Queue
LeetCode 1464 note: all values are positive, so take the two largest a and b and return (a - 1)(b - 1)
LeetCode 2357: Make Array Zero by Subtracting Equal Amounts
·1 min
LeetCode Easy Array Hash-Table Greedy Sorting
LeetCode 2357 note: each operation zeroes the group of the smallest positive value, so the answer is the number of distinct positive values
LeetCode 1122: Relative Sort Array
·1 min
LeetCode Easy Array Hash-Table Sorting Counting-Sort
LeetCode 1122 note: count first, emit values in arr2’s order, then append the remaining values in ascending order
LeetCode 888: Fair Candy Swap
·2 mins
LeetCode Easy Array Hash-Table Binary-Search Sorting
LeetCode 888 note: equal sums after swapping x and y means y = x + (sumB - sumA) / 2; put B in a set and check each x from A
LeetCode 645: Set Mismatch
·2 mins
LeetCode Easy Array Hash-Table Bit-Manipulation Sorting
LeetCode 645 note: use sums: missing = sum of 1..n - sum of the set, duplicate = array sum - sum of the set