Given an array of integers, write a function to find the second largest number in the array. The function should return -1 if the array has less than two elements. Function signature: int second_largest(int arr[], int size) Example: Input: arr = [1, 2, 3, 4, 5], size = 5 Output: 4 Input: arr = [1], size = 1 Output: -1 Notes: The function should work for arrays of any size. You can assume that the elements of the array are unique and not sorted in any particular order. This problem requires the use of loops, conditional statements, and basic array operations, and it can be solved using a variety of algorithms. A brute-force approach would be to compare each element with all other elements in the array to find the largest and second largest numbers, but this would have a time complexity of O(n^2). A more efficient solution would be to use a single loop to iterate through the array, updating the values of the largest and second largest numbers as needed.
Given an array of integers, write a function to find the second largest number in the array. The function should return -1 if the array has less than two elements.
Function signature: int second_largest(int arr[], int size)
Example:
Input: arr = [1, 2, 3, 4, 5], size = 5
Output: 4
Input: arr = [1], size = 1
Output: -1
Notes:
The function should work for arrays of any size.
You can assume that the elements of the array are unique and not sorted in any particular order.
This problem requires the use of loops, conditional statements, and basic array operations, and it can be solved using a variety of
Step by step
Solved in 3 steps with 1 images