← Loops

Find Second Largest

Easy
Python
def second_max(nums):
    first=second=float('-inf')
    for n in nums:
        if n>first: second=first; first=n
        elif n>second: second=n
    return second
Java
public int secondMax(int[] nums){
    int first=Integer.MIN_VALUE,second=Integer.MIN_VALUE;
    for(int n:nums){
        if(n>first){second=first;first=n;}
        else if(n>second) second=n;
    } return second;
}

Key Insight

float('-inf') vs Integer.MIN_VALUE. elif vs else if.

Python → Java Differences

  • float('-inf') vs Integer.MIN_VALUE
  • elif vs else if
  • Two-variable tracking identical
Python
def second_max(nums):
    first=second=float('-inf')
    for n in nums:
        if n>first: second=first; first=n
        elif n>second: second=n
    return second
Java
public int secondMax(int[] nums){
    int first=Integer.MIN_VALUE,second=Integer.MIN_VALUE;
    for(int n:nums){
        if(n>first){second=first;first=n;}
        else if(n>second) second=n;
    } return second;
}

Algorithm Steps

1. Track top two values