Maximum Occurrence Element In An Array
Find maximum occurrence element in an array in O(n) time and O(1) extra space
Note: Maximum occurrence element which occurred more than half of array.
Algorithm:
- Set count = 0
- Iterate all array element from start to end
- If count == 0 then
- Set maxiOccurrenceElement = array[index]
- Set increase count (i.e. count++)
- Else If maxiOccurrenceElement == array[index] then
- Set increase count (i.e. count++)
- Else
- Set decrease count (i.e. count–)
- If count == 0 then
- Validate maxiOccurrenceElement occurred more than half of array.
Latest Source Code:
Github: MaxOccurrenceElement.java
Output:
Array: [1, 2, 1, 3, 1, 5, 1, 6, 1, 2, 2, 1, 4, 1, 1] Max occurrence element: 1