admin@onlinelearningcenter.in (+91) 7 999 01 02 03

Find the largest three elements in an array

suraz Ghimire
5 Posts

Given an Array of Duplicate Element

12, 13, 1, 34, 34, 1

 

Find the Unique Large 3 Elements

Approach 1:

package in.olc.array.easy

object _1_1Largest3DistinctElement {

  def findLargest3DistinctElement(arr: Array[Int]): Unit = {
    if(arr.length<3){
      throw new Exception("Please provide Array of atleast 3 Elements")
    }
  var first,second,third:Int=Int.MinValue
    arr.foreach(num => {
    if(num>first){
      third=second
      second=first
      first=num
    }
    else if(num>first && num>second){
      third=second
      second=num
    }
    else if(num>first && num>second && num>third){
      third=num
    }
    })
    println(s"Three largest elements are $first,$second,$third")
  }

  def main(args: Array[String]): Unit = {
    val arr=Array(12, 13, 1, 34, 34, 1 )
    findLargest3DistinctElement(arr)
  }
}

Time Complexity: O(n)
Auxiliary Space: O(1)

 

In case you have better solution, Please do share your Answer in the comment section. 

Lets Learn Together

 

 

Published By : suraz Ghimire
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Comments

Jquery Comments Plugin