codinasion-archive / codinasion-monorepo

Community Monorepo
https://codinasion.org
MIT License
52 stars 167 forks source link

Write a Java program to find the largest two elements in an array #5042

Open harshraj8843 opened 10 months ago

harshraj8843 commented 10 months ago

Description

Write a Java program to find the largest two elements in an array

Input: arr[] = {12, 13, 1, 10, 34, 1}
Output: The largest two elements are 34 and 13

Input: arr[] = {10, 5, 10}
Output: The largest two elements are 10 and 5

Input: arr[] = {10, 10, 10}
Output: The largest two elements are 10 and 10
How to contribute - Comment `!assign` to assign this issue to yourself - Fork this repository - Create a new branch - Save the solution in `program/program/find-the-largest-two-elements-in-an-array/FindTheLargestTwoElementsInAnArray.java` - Commit the changes - Create a pull request
codinasion-bot[bot] commented 10 months ago

👋🏻 Hey @harshraj8843

💖 Thanks for opening this issue 💖

A team member should be by to give feedback soon.

zackbmz commented 10 months ago

!assign

DongJu-Na commented 9 months ago

!assign

codinasion-bot[bot] commented 9 months ago

Hey @DongJu-Na, this issue is already assigned to @zackbmz! cc/ @codinasion/codinasion

savarsri commented 6 months ago

import java.util.Arrays;

public class Main { public static void main(String[] args) { int[] array = {5, 8, 1, 6, 3, 9, 2, 7, 4};

    findLargestTwo(array);
}

public static void findLargestTwo(int[] array) {
    if (array.length < 2) {
        System.out.println("Array should have at least two elements.");
        return;
    }

    int firstLargest = Integer.MIN_VALUE;
    int secondLargest = Integer.MIN_VALUE;

    for (int num : array) {
        if (num > firstLargest) {
            secondLargest = firstLargest;
            firstLargest = num;
        } else if (num > secondLargest && num != firstLargest) {
            secondLargest = num;
        }
    }

    if (secondLargest == Integer.MIN_VALUE) {
        System.out.println("There are no distinct largest elements in the array.");
    } else {
        System.out.println("The largest two elements in the array are: " + firstLargest + " and " + secondLargest);
    }
}

}

abhinav-selvaraj commented 5 months ago

!assign

codinasion-bot[bot] commented 5 months ago

Hey @abhinav-selvaraj, this issue is already assigned to @zackbmz! cc/ @codinasion/codinasion

GuyBernstein commented 5 months ago

!assign

codinasion-bot[bot] commented 5 months ago

Hey @GuyBernstein, this issue is already assigned to @zackbmz! cc/ @codinasion/codinasion

PietervHa commented 5 months ago

!assign

codinasion-bot[bot] commented 5 months ago

Hey @PietervHa, this issue is already assigned to @zackbmz! cc/ @codinasion/codinasion