Solution #1: Sorting is one obvious way, but, there is another efficient way. Here is the code,
int secondMax(int* arr, int len) { int max = 0; int sMax = 0; int i = 0; for(i=0; i < len; i++) { int curr = arr[i]; if(curr > max) { sMax = max; max = curr; } else if(curr > sMax) sMax = curr; } return sMax; } int main() { int arr[5] = {3, 2, 5, 1, 4}; printf("Second Max: %d\n", secondMax(arr, 5)); return 0; }
No comments:
Post a Comment