Election took place with a list of candidates contesting. Each candidate has an id associated with the candidate name. You are given an array of votes represented by ids. Write a program to find the winner of the election. If there is more than one candidate with the highest votes then there would be multiple winners, print all the winners’ names.
[1: JOHN, 2: BOB, 3:CARL] Votes = [1, 1, 2, 1, 3, 2] Winner: JOHN [1: JOHN, 2: BOB, 3:CARL] Votes = [1, 1, 2, 1, 3, 2, 2] Winner: JOHN, BOB
- Create a HashMap with candidate id as key and no of votes to that candidate as value.
- Iterate the given votes and construct the map.( If id is present in the map increments its value count else insert the id with value 1 to the map.)
- Now iterate the map to find the id/ids with the maximum number of votes.
- See the code below for better understanding.
Election winner: [JOHN, BOB]