3478. Choose K Elements With Maximum Sum Medium

@problem@discussion
#Array#Sorting#Heap (Priority Queue)



1/**
2 * [3478] Choose K Elements With Maximum Sum
3 *
4 * You are given two integer arrays, nums1 and nums2, both of length n, along with a positive integer k.
5 * For each index i from 0 to n - 1, perform the following:
6 * 
7 * 	Find all indices j where nums1[j] is less than nums1[i].
8 * 	Choose at most k values of nums2[j] at these indices to maximize the total sum.
9 * 
10 * Return an array answer of size n, where answer[i] represents the result for the corresponding index i.
11 *  
12 * <strong class="example">Example 1:
13 * <div class="example-block">
14 * Input: <span class="example-io">nums1 = [4,2,1,5,3], nums2 = [10,20,30,40,50], k = 2</span>
15 * Output: <span class="example-io">[80,30,0,80,50]</span>
16 * Explanation:
17 * 
18 * 	For i = 0: Select the 2 largest values from nums2 at indices [1, 2, 4] where nums1[j] < nums1[0], resulting in 50 + 30 = 80.
19 * 	For i = 1: Select the 2 largest values from nums2 at index [2] where nums1[j] < nums1[1], resulting in 30.
20 * 	For i = 2: No indices satisfy nums1[j] < nums1[2], resulting in 0.
21 * 	For i = 3: Select the 2 largest values from nums2 at indices [0, 1, 2, 4] where nums1[j] < nums1[3], resulting in 50 + 30 = 80.
22 * 	For i = 4: Select the 2 largest values from nums2 at indices [1, 2] where nums1[j] < nums1[4], resulting in 30 + 20 = 50.
23 * </div>
24 * <strong class="example">Example 2:
25 * <div class="example-block">
26 * Input: <span class="example-io">nums1 = [2,2,2,2], nums2 = [3,1,2,3], k = 1</span>
27 * Output: <span class="example-io">[0,0,0,0]</span>
28 * Explanation:
29 * Since all elements in nums1 are equal, no indices satisfy the condition nums1[j] < nums1[i] for any i, resulting in 0 for all positions.
30 * </div>
31 *  
32 * Constraints:
33 * 
34 * 	n == nums1.length == nums2.length
35 * 	1 <= n <= 10^5
36 * 	1 <= nums1[i], nums2[i] <= 10^6
37 * 	1 <= k <= n
38 * 
39 */
40pub struct Solution {}
41
42// problem: https://leetcode.com/problems/choose-k-elements-with-maximum-sum/
43// discuss: https://leetcode.com/problems/choose-k-elements-with-maximum-sum/discuss/?currentPage=1&orderBy=most_votes&query=
44
45// submission codes start here
46
47impl Solution {
48    pub fn find_max_sum(nums1: Vec<i32>, nums2: Vec<i32>, k: i32) -> Vec<i64> {
49        
50    }
51}
52
53// submission codes end
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn test_3478() {
61    }
62}
63

Back
© 2026 bowen.ge All Rights Reserved.