CC-19 : Sum of numbers between K1 smallest and K2 smallest.
Description:
Given array of integers, find the K1 smallest and K2 smallest numbers. Then find the sum of all numbers within array in terms of magnitude that are between K1 smallest and K2 smallest numbers.
Test cases and expected outputs:
| Input Parameters | Expected outputs |
|---|---|
| Nums : 1,2,3,4,5,6,7,8,9 |
Sum between 3rd smallest and 7th smallest number is: 15 |
Pseudocode:
Method rearrange(str):
| This method takes k integer arrays named nums as parameter. We need to find top K1 and K2 smallest integers and value of K1 and K2 are also received as input parameters. |
| Initialize a PriorityQueue instance named heap. Provide an instance of Collections.reverOrder() to the constructor the PriorityQueue to sort by magnitude of the integers. |
| Iterate though nums from index 0 to index chars.length-1 using idx as member variable:
Add num[idx] to the heap.
If heapsize is > K2, then remove top element from the heap.
<
|
| Remove top element from the heap. |
| Initialize variable sumBetween to 0. |
| While heap size is > K1:
Remove to element from heap and add it to sumBetween.
|
| Return sumBetween, as now it is the sum of all numbers within array in terms of magnitude that are between K1 smallest and K2 smallest numbers. |
Code:
public int sumBetweenK1SmallestAndK2Smallest(int[] nums, int k1, int k2) {
PriorityQueue<Integer> heap=new PriorityQueue<Integer>(Collections.reverseOrder());
for (int idx=0; idx<nums.length; idx++) {
heap.offer(nums[idx]);
if (heap.size() > k2) {
heap.poll();
}
}
heap.poll();
int sumBetween=0;
while (heap.size() > k1) {
sumBetween+=heap.remove();
}
return sumBetween;
}
Click here to download and run code and test cases !
| About Us | Privacy Policy | Contact us |