## Tuesday, August 30, 2016

### Third largest element in an array of distinct elements - GeeksforGeeks

LeetCode 414 - Third Maximum Number
Third largest element in an array of distinct elements - GeeksforGeeks
Given an array of distinct elements, find third largest element in it.
`void` `thirdLargest(``int` `arr[], ``int` `arr_size)`
`{`
`    ``/* There should be atleast three elements */`
`    ``if` `(arr_size < 3)`
`    ``{`
`        ``printf``(``" Invalid Input "``);`
`        ``return``;`
`    ``}`
`    ``// Initialize first, second and third Largest element`
`    ``int` `first = arr[0], second = INT_MIN, third = INT_MIN;`
`    ``// Traverse array elements to find the third Largest`
`    ``for` `(``int` `i = 1; i < arr_size ; i ++)`
`    ``{`
`        ``/* If current element is gretaer than first,`
`           ``then update both first and second */`
`        ``if` `(arr[i] > first)`
`        ``{`
`            ``third  = second;`
`            ``second = first;`
`            ``first  = arr[i];`
`        ``}`
`        ``/* If arr[i] is in between first and second */`
`        ``else` `if` `(arr[i] > second)`
`        ``{`
`            ``third = second;`
`            ``second = arr[i];`
`        ``}`
`        ``/* If arr[i] is in between second and third */`
`        ``else` `if` `(arr[i] > third)`
`            ``third = arr[i];`
`    ``}`
`    ``printf``(``"The third Largest element is %d\n"``, third);`
`}`
`void` `thirdLargest(``int` `arr[], ``int` `arr_size)`
`{`
`    ``/* There should be atleast three elements */`
`    ``if` `(arr_size < 3)`
`    ``{`
`        ``printf``(``" Invalid Input "``);`
`        ``return``;`
`    ``}`
`    ``// Find first largest element`
`    ``int` `first = arr[0];`
`    ``for` `(``int` `i = 1; i < arr_size ; i++)`
`        ``if` `(arr[i] > first)`
`            ``first = arr[i];`
`    ``// Find second largest element`
`    ``int` `second = INT_MIN;`
`    ``for` `(``int` `i = 0; i < arr_size ; i++)`
`        ``if` `(arr[i] > second && arr[i] < first)`
`            ``second = arr[i];`
`    ``// Find third largest element`
`    ``int` `third = INT_MIN;`
`    ``for` `(``int` `i = 0; i < arr_size ; i++)`
`        ``if` `(arr[i] > third && arr[i] < second)`
`            ``third = arr[i];`
`    ``printf``(``"The third Largest element is %d\n"``, third);`
`}`