Tome Cache Validator 35 — Problem Statement & Solution Guide
Problem Description
Given an array of metrics and an integer K, return the sum of the K largest numbers in the array.
Examples
Input
[10, 20, 30, 40, 50], 3
Output
120
Explanation: Step-by-step: with input [10, 20, 30, 40, 50] and K = 3, we sort the array in descending order to get [50, 40, 30, 20, 10]. Then, we sum the 3 largest numbers: 50 + 40 + 30 = 120.
Input
[1, 2, 3, 4, 5], 2
Output
9
Explanation: Step-by-step: with input [1, 2, 3, 4, 5] and K = 2, we sort the array in descending order to get [5, 4, 3, 2, 1]. Then, we sum the 2 largest numbers: 5 + 4 = 9.
Constraints
- 1 <= N <= 10^5
- -10^4 <= metrics[i] <= 10^4
- 1 <= K <= N
Optimal Approach & Strategy
Use Monotonic Stack technique to process inputs in O(N) linear time.
Brute Force Approach
Check all possible combinations in O(N^2) time.
Verified Code Solutions
function solution(nums, k) { return nums.sort((a, b) => b - a).slice(0, k).reduce((a, b) => a + b, 0); }class Solution { public: int solution(vector<int>& nums, int k) { sort(nums.rbegin(), nums.rend()); int sum = 0; for (int i = 0; i < k; i++) { sum += nums[i]; } return sum; } };class Solution { public int solution(int[] nums, int k) { Arrays.sort(nums); int sum = 0; for (int i = nums.length - 1; i >= nums.length - k; i--) { sum += nums[i]; } return sum; } }def solution(nums, k): return sum(sorted(nums, reverse=True)[:k])function solution(nums, k) { return nums.sort((a, b) => b - a).slice(0, k).reduce((a, b) => a + b, 0); }Asked in Top Tech Interviews
Solve in Interative Editor
Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.