Dsa in python
Dsa in python
class Solution:
n = len(arr)
if n < 2:
return -1
second = first
first = num
second = num
if second == float('-inf'):
return -1
else:
return second
Algorithm:
1. Input Validation:
o If the array has fewer than two elements, return -1 because a second largest element
cannot exist.
2. Initialize Variables:
o Use two variables, first and second, initialized to negative infinity (float('-inf')):
4. Check Result:
o If second is still float('-inf'), it means there was no valid second largest element (e.g.,
all elements were the same), so return -1.
Stepwise Execution:
1. Initialization:
o first = float('-inf')
o second = float('-inf')
first = 12
second = first = 12
first = 35
second = 10
o Iteration 5 (num = 34):
second = 34
3. Final Check: