Qn: An array of N numbers are passed as input. Write a java program logic to print the leader element of an array which is greater than all the elements to it's right. The Boundary is 1<= N =>999
Note: the right most element is always leader
-By venkat, Last Update On 12th June,2019 10:11 pm

Finding array leader elements

இங்கு N-ன் boundary condition 1<= N =>999 இவ்வாறு கொடுக்கப்பட்டுள்ளது. ஆகையால் array-ன் maximum size 999 என்று தெளிவாக தேறிகிறது. அதாவது 1-லிருந்து 999-வரை எத்தனை array elements வேண்டுமானாலும் dynamic-ஆக கொடுதுகொள்ளலாம். ஆகையால் int arr[999]; என்று declare செய்யப்பட்டுள்ளது.

rightmost element அதாவது last element always leader ஆகையால் அவற்றை நேரடியாகவே print செய்துவிடலாம்.

import java.util.Scanner;
public class FindLeader {
    public static void main(String[] args) {
        int n, i, j, status = 0;
        int arr[] = new int[999];
        System.out.print("Enter how many elements you want: ");
        Scanner sn = new Scanner(System.in);
        n = sn.nextInt();
        System.out.print("Enter all the elements with space : ");
        for (i = 0; i < n; i++) {
            arr[i] = sn.nextInt();
        }
        System.out.print("The array leaders are : ");
        for (i = 0; i < n; i++) {
            if (i + 1 == n) {// print last elemnt
                System.out.print(arr[i]);
                break;
            } else {
                for (j = i + 1; j < n; j++) {
                    // checking is it greatest to all of its right side
                    if (arr[i] > arr[j]) {
                        status = 1;
                    } else {
                        status = 0;
                        break;
                    }
                }
                if (status == 1) {
                    // this is greatest to all of its right side elements
                    System.out.print(arr[i] + " ");
                }
            }
        }
    }

}
Output:
Enter how many elements you want: 6
Enter all the elements with space : 10 17 4 3 5 2
The array leader elements are : 17 5 2

Pgcomments

Comments

Mustaq 10th October,2023 05:24 pm
Super