Given an array of positive integers arr[], return the second largest element from the…
- User
Given an array of positive integers arr[], return the second largest element from the array. If the second largest element doesn't exist then return -1.
Note: The second largest element should not be equal to the largest element.
Examples:
Input: arr[] = [12, 35, 1, 10, 34, 1] Output: 34 Explanation: The largest element of the array is 35 and the second largest element is 34. Input: arr[] = [10, 5, 10] Output: 5 Explanation: The largest element of the array is 10 and the second largest element is 5. Input: arr[] = [10, 10, 10] Output: -1 Explanation: The largest element of the array is 10 and the second largest element does not exist. Constraints: 2 ≤ arr.size() ≤ 105 1 ≤ arr[i] ≤ 105
- Assistant
To solve this problem efficiently, we can iterate through the array while keeping track of the largest and second-largest elements. Here's the approach:
-
Initialize two variables:
largestto keep track of the largest element found so far.second_largestto keep track of the second-largest element found so far.
-
Iterate over each element
ain the array:- If
ais greater thanlargest:- Update
second_largestto be the previouslargest. - Update
largestto bea.
- Update
- If
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.