Javascript Program to Find k maximum elements of array in original order
Given an array arr[] and an integer k, we need to print k maximum elements of given array. The elements should printed in the order of the input.
Note : k is always less than or equal to n.
Examples:
Input : arr[] = {10 50 30 60 15}
k = 2
Output : 50 60
The top 2 elements are printed
as per their appearance in original
array.
Input : arr[] = {50 8 45 12 25 40 84}
k = 3
Output : 50 45 84
Method 1: We search for the maximum element k times in the given array. Each time we find one maximum element, we print it and replace it with minus infinite (Number.MIN_SAFE_INTEGER in Javascript) in the array. Also, the position of all k maximum elements is marked using an array so that with the help of that array we can print the elements in the order given in the original array. The time complexity of this method is O(n*k).
Javascript
<script>
function printMax(arr, k, n)
{
var brr = Array(n).fill(0);
var crr = Array(n)
for ( var i=0;i<n;i++)
{
crr[i]=arr[i];
}
for ( var i=0;i<k;i++)
{
var maxi=Number.MIN_SAFE_INTEGER;
var index;
for ( var j=0;j<n;j++)
{
if (maxi<arr[j])
{
maxi=arr[j];
index=j;
}
}
brr[index]=1;
arr[index]=Number.MIN_SAFE_INTEGER;
}
for ( var i=0;i<n;i++)
{
if (brr[i]==1)
document.write(crr[i]+ " " );
}
}
var arr = [ 50, 8, 45, 12, 25, 40, 84 ];
var n = arr.length;
var k = 3;
printMax(arr, k, n);
</script>
|
Time Complexity: O(n*k)
Auxiliary Space: O(n)
Method 2: In this method, we store the original array in a new array and will sort the new array in descending order. After sorting, we iterate the original array from 0 to n and print all those elements that appear in first k elements of new array. For searching, we can do Binary Search.
Javascript
<script>
function printMax(arr, k, n)
{
var brr = arr.slice();
brr.sort((a, b) => b - a);
for ( var i = 0; i < n; ++i)
if (brr.indexOf(arr[i]) < k)
document.write(arr[i] + " " );
}
var arr = [ 50, 8, 45, 12, 25, 40, 84 ];
var n = arr.length;
var k = 3;
printMax(arr, k, n);
</script>
|
Output:
50 45 84
Time Complexity: O(n Log n) for sorting.
Auxiliary Space: O(n)
Please refer complete article on Find k maximum elements of array in original order for more details!
Last Updated :
07 Dec, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...