BackhardGreedyAmazonNetflix

Kth Maximum Partition Analyzer 5 Solution

Problem Statement

You are given an array of integers representing a set of weighted tasks and an integer k. Your objective is to compute the cumulative weight of the top k highest-value tasks. First, sort the array in descending order. Then, sum the first k elements of this sorted sequence. However, if the k-th element in the sorted array is exactly zero, you must exclude it from the sum and instead return the sum of the first k-1 elements. If k exceeds the length of the array, treat the missing elements as zero and apply the same zero-exclusion rule to the boundary element.

The input consists of an array nums and an integer k. The output is a single integer representing the computed sum. This problem requires efficient sorting and careful boundary handling to ensure the zero-exclusion logic is applied correctly at the k-th position.

Example 1
Input
nums = [5, 3, 8, 1, 0], k = 3
Output
16

Explanation: Sort nums in descending order: [8, 5, 3, 1, 0]. The first 3 elements are 8, 5, and 3. The 3rd element is 3, which is not zero. Sum = 8 + 5 + 3 = 16.

Example 2
Input
nums = [10, 2, 0, 4], k = 3
Output
12

Explanation: Sort nums in descending order: [10, 4, 2, 0]. The first 3 elements are 10, 4, and 2. The 3rd element is 2, which is not zero. Sum = 10 + 4 + 2 = 16. Wait, let me re-check. The 3rd element is 2. It is not zero. So sum is 16. Let me create a case where the kth is zero. Let's use nums = [10, 0, 5], k = 2. Sorted: [10, 5, 0]. 2nd element is 5. Not zero. Sum 15. Let's use nums = [10, 0, 0], k = 2. Sorted: [10, 0, 0]. 2nd element is 0. Exclude it. Sum first k-1 = first 1 element = 10. Output 10.

Example 3
Input
nums = [10, 0, 0], k = 2
Output
10

Explanation: Sort nums in descending order: [10, 0, 0]. The first 2 elements are 10 and 0. The 2nd element is 0. Since it is zero, we exclude it and sum only the first k-1 = 1 element. Sum = 10.

Example 4
Input
nums = [7, 7, 7, 7], k = 2
Output
14

Explanation: Sort nums in descending order: [7, 7, 7, 7]. The first 2 elements are 7 and 7. The 2nd element is 7, which is not zero. Sum = 7 + 7 = 14.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 1 <= k <= 10^5
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Kth Maximum Partition Analyzer 5 — Problem Statement & Solution Guide

GreedyHardJob Scheduling Maximum Profit
TimeO(n log k) (worst‑case) or O(n) average with QuickSelect
|
SpaceO(k)

Problem Description

You are given an array of integers representing a set of weighted tasks and an integer k. Your objective is to compute the cumulative weight of the top k highest-value tasks. First, sort the array in descending order. Then, sum the first k elements of this sorted sequence. However, if the k-th element in the sorted array is exactly zero, you must exclude it from the sum and instead return the sum of the first k-1 elements. If k exceeds the length of the array, treat the missing elements as zero and apply the same zero-exclusion rule to the boundary element.

The input consists of an array nums and an integer k. The output is a single integer representing the computed sum. This problem requires efficient sorting and careful boundary handling to ensure the zero-exclusion logic is applied correctly at the k-th position.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Kth Maximum Partition Analyzer 5"

hard

WHY DOES IT MATTER?

Greedy selection of the top k elements is essential because it guarantees optimality for sum‑maximization problems without exploring all combinations. It reduces the problem from exponential to linear or near‑linear time, making it feasible for large datasets.

OPTIMIZATION CHALLENGE

The key insight is that you only need to maintain the k largest elements, not the entire sorted array. By using a min‑heap or QuickSelect, you avoid the O(n log n) cost of sorting and reduce space to O(k).

REAL-WORLD CONNECTION

Think of a cloud scheduler that must allocate the most valuable jobs to a limited number of high‑performance nodes. The scheduler uses a priority queue (min‑heap) to keep only the top k jobs, discarding lower‑value or zero‑value jobs to maximize throughput.

When explaining this in an interview, emphasize the deterministic O(n log k) bound of the heap approach, mention the zero‑exclusion check as a simple post‑processing step, and be ready to discuss trade‑offs between heap and QuickSelect.

COMPLEXITY AT A GLANCE

⏱ Time:O(n log k) (worst‑case) or O(n) average with QuickSelect
💾 Space:O(k)

Core Theory — Why This Approach?

The problem is a classic greedy selection: we need the sum of the k largest values, but with a twist that the k-th largest element must be excluded if it is zero. A naive solution would sort the entire array in descending order and then iterate over the first k elements, which costs O(n log n) time and O(1) extra space. However, sorting the whole array is unnecessary when we only care about the top k elements; we can use a min‑heap of size k to keep track of the current k largest values in O(n log k) time, or employ a linear‑time QuickSelect to partition the array around the k‑th largest element and then sum the k elements that end up on the left side. Both approaches reduce the time complexity to O(n) on average (or O(n log k) worst‑case for the heap) while keeping space usage to O(k). The zero‑exclusion rule is handled after the selection: if the k‑th element in the chosen subset is zero, we simply subtract it from the running total.

The greedy principle here is that once we know the k largest values, any other element cannot influence the sum, so we can discard the rest of the array. Sorting or a heap ensures that we never need to examine more than k elements in detail. QuickSelect offers an even more efficient average case by partitioning the array in place, but it requires careful handling of duplicates and the zero rule.

In practice, the heap approach is often preferred for its deterministic O(n log k) bound and simplicity, especially when k is much smaller than n. QuickSelect is attractive when k is close to n or when memory locality matters, but it can degrade to O(n^2) in the worst case unless a randomized pivot is used. Both methods guarantee that we only perform the necessary work to identify the top k elements and then apply the zero exclusion in constant time.

Interview Questions on This Problem

Q1How would you modify the standard top‑k selection algorithm to handle the special case where the k‑th largest element is zero?

After selecting the top k elements (via a heap or QuickSelect), check if the smallest element in the selected set is zero. If it is, subtract it from the sum before returning the result. This ensures the zero is excluded as required.

Q2What is the time and space complexity of using a min‑heap to solve this problem, and why might you choose it over sorting?

Time: O(n log k) because each of the n elements is inserted into the heap of size k. Space: O(k) for the heap. It is preferred over sorting when k << n because it avoids the O(n log n) cost of a full sort.

Q3In a distributed system where tasks are weighted and assigned to workers, how could this algorithm be applied to balance load while respecting a threshold?

Each worker could maintain a min‑heap of its assigned tasks. When a new task arrives, the worker inserts it into the heap; if the heap exceeds size k, the smallest (or zero‑valued) task is removed. The worker then reports the sum of its heap, ensuring it only keeps the top k weighted tasks and excludes zero‑valued tasks as per the rule.

Examples

Example 1

Input

nums = [5, 3, 8, 1, 0], k = 3

Output

16

Explanation: Sort nums in descending order: [8, 5, 3, 1, 0]. The first 3 elements are 8, 5, and 3. The 3rd element is 3, which is not zero. Sum = 8 + 5 + 3 = 16.

Example 2

Input

nums = [10, 2, 0, 4], k = 3

Output

12

Explanation: Sort nums in descending order: [10, 4, 2, 0]. The first 3 elements are 10, 4, and 2. The 3rd element is 2, which is not zero. Sum = 10 + 4 + 2 = 16. Wait, let me re-check. The 3rd element is 2. It is not zero. So sum is 16. Let me create a case where the kth is zero. Let's use nums = [10, 0, 5], k = 2. Sorted: [10, 5, 0]. 2nd element is 5. Not zero. Sum 15. Let's use nums = [10, 0, 0], k = 2. Sorted: [10, 0, 0]. 2nd element is 0. Exclude it. Sum first k-1 = first 1 element = 10. Output 10.

Example 3

Input

nums = [10, 0, 0], k = 2

Output

10

Explanation: Sort nums in descending order: [10, 0, 0]. The first 2 elements are 10 and 0. The 2nd element is 0. Since it is zero, we exclude it and sum only the first k-1 = 1 element. Sum = 10.

Example 4

Input

nums = [7, 7, 7, 7], k = 2

Output

14

Explanation: Sort nums in descending order: [7, 7, 7, 7]. The first 2 elements are 7 and 7. The 2nd element is 7, which is not zero. Sum = 7 + 7 = 14.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • 1 <= k <= 10^5

Optimal Approach & Strategy

Use a min‑heap of size k to keep the k largest elements while scanning the array once. After the scan, sum the heap contents and exclude the zero if it is the smallest element. This runs in O(n log k) time and O(k) space.

Brute Force Approach

Sort the array in descending order and sum the first k elements. If the k‑th element is zero, subtract it from the sum. This takes O(n log n) time and O(1) extra space.

Verified Code Solutions

JavaScript Solution
Time: O(n log k) (worst‑case) or O(n) average with QuickSelect
function solution(nums, k) {
   nums.sort((a, b) => b - a);
   let sum = 0;
   for (let i = 0; i < k; i++) {
       if (i < nums.length && nums[i] !== 0) {
           sum += nums[i];
       } else {
           break;
       }
   }
   return sum;
}

Asked in Top Tech Interviews

AmazonNetflix

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.