Find Subsequence of Length K With the Largest Sum
Real-world version: Keeping the k Best Readings in PlaceThe statement here is our own: the same inputs, outputs and technique.
A row of readings is given, and k of them are to be kept so that their total is as large as possible.
Several choices can tie on total, so the choice is pinned down like this: rank the positions of the row by their reading, largest first, and settle any tie in favour of the earlier position. Keep the first k positions of that ranking.
Return the kept readings in the order their positions appear in the row.
Examples
Example 1
- Input
- readings = [1, 9, 2, 8, 3, 7], k = 3
- Output
- [9, 8, 7]
The three largest readings are 9, 8 and 7, and they are reported in the order the row holds them.
Example 2
- Input
- readings = [2, 5, 2], k = 2
- Output
- [2, 5]
The largest reading is 5 and one of the two readings of 2 joins it. The tie goes to the earlier of the two, so the report reads 2 then 5.
Example 3
- Input
- readings = [-5, -4, -3], k = 1
- Output
- [-3]
Only one reading is kept, and the largest of the three sits at the end of the row.
Constraints
- 1 <= readings.length <= 1000
- -10^5 <= readings[i] <= 10^5
- 1 <= k <= readings.length
The signature
The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.
def max_subsequence(readings: list[int], k: int) -> list[int]:public int[] maxSubsequence(int[] readings, int k)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 15 test cases: 15 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's
More on the same topics
- High FiveReal-world version: Top Five Average per ApprenticeEasy
- Make Array Zero by Subtracting Equal AmountsReal-world version: Rounds Needed to Clear Every ReadingEasy
- Top K Frequent ElementsReal-world version: Most Reported Calibration OffsetsMedium
- Task SchedulerReal-world version: Press Die CooldownMedium