Leaders in an array
An element is leader if it is greater than all the elements to its right. The last array element is a leader by default.
Example:
Input: {16, 17, 4, 3, 5, 2}
Output: 2, 5, 17
Concept:
Scan form right. Keep track of maximum element. If the maximum changes print the element and update the maximum. Time complexity O(n).
Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[] a = {1,10,4,5,3,2};
int n = a.length;
int max = a[n-1];
System.out.print(max+" ");
for(int i=n-2; i>=0; i--){
if(a[i] > max){
System.out.print(a[i]+" ");
max = a[i];
}
}
}
}
Output:
Example:
Input: {16, 17, 4, 3, 5, 2}
Output: 2, 5, 17
Concept:
Scan form right. Keep track of maximum element. If the maximum changes print the element and update the maximum. Time complexity O(n).
Code:
import java.util.*;
public class Solution {
public static void main(String[] args) {
int[] a = {1,10,4,5,3,2};
int n = a.length;
int max = a[n-1];
System.out.print(max+" ");
for(int i=n-2; i>=0; i--){
if(a[i] > max){
System.out.print(a[i]+" ");
max = a[i];
}
}
}
}
Output:
2 3 5 10
Comments
Post a Comment