Join Regular Classroom : Visit ClassroomTech

Accenture Coding Question | Superior Array Element | CodeWindow

Superior Array Element

In an array, a superior element is one that is greater than all elements to its right. the rightmost element will always be considered as a superior element.

Here, the function accepts an integer array ‘arr’ and its length ‘n’. Implement the function to find and return the number of superior element in the array ‘arr’.

Assumptions:
1. n>0
2. Array index starts from 0.

Example 1:
Input 1: 7 9 5 2 8 7

Output: 3
Explanation:
9 is greater than all the elements to its right, 8 is greater than the element to its right, and 7 is the rightmost element. hence total 3 superior elements.

Sample Input:
2 8 9 7 4 2

Sample Output:
4

Solution in Python 3:

# https://codewindow.in

arr=list(map(int, input().split()))
count=0
for i in range(len(arr)-1):
    j=i+1
    arr_n=arr[j:]
    m=max(arr_n)
    if arr[i] > m:
        count+=1
print(count+1)

# Join Telegram @codewindow

Solution in JAVA :

//https://codewindow.in
//join our telegram channel @codewindow

import java.io.*;
import java.lang.*;
import java.util.*;

class CodeWindow {
    public static void main(String[] args) throws Exception
    {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String arr[] = br.readLine().split(" ");
        int nums[] = new int[arr.length];
        for(int i=0;i<arr.length;i++)
            nums[i] = Integer.parseInt(arr[i]);
        int count = 0;
        for(int i=0;i<nums.length;i++) {
            int flag = 1;
            for(int j=i+1;j<nums.length;j++) {
                if(nums[i] < nums[j]) {
                    flag = 0;
                    break;
                }
            }
            if(flag == 1)
                count++;
        }
        System.out.println(count);
    }
}

Solution in C++ :

//https://codewindow.in
//join our telegram channel @codewindow

#include <bits/stdc++.h>
#include <iostream>

using namespace std;
 
int main()
{
    vector<int> arr;
    int input;
    while(cin >> input) {
        arr.push_back(input);
    }
    int count = 0;
    for(int i=0;i<arr.size();i++) {
        int flag = 1;
        for(int j=i+1;j<arr.size();j++) {
            if(arr[i] < arr[j]) {
                flag = 0;
                break;
            }
        }
        if(flag == 1)
            count++;
    }
    cout << count;
    return 0;
}

Output:

7 9 5 2 8 7
3
Recent Posts
Pages