Find Maximum Element Using Pointer Walk

Code

#include <stdio.h>

int find_max_element(int *ptr, int n) {
    // Your logic here
    int temp=0,temp2=0,temp1=0;
    while(n)
    {
        if(*ptr>temp)
        {
            temp=*ptr;
        }
        else if(*ptr<temp1)
        {
             temp2=temp1;
            temp1=*ptr;
        }
        else 
        temp1=*ptr;
        ptr++;
        n--;
    }
    if(temp>0)
    return temp;
    else return temp2;
}

int main() {
    int n;
    scanf("%d", &n);

    int arr[100];
    for (int i = 0; i < n; i++) {
        scanf("%d", &arr[i]);
    }

    int result = find_max_element(arr, n);
    printf("%d", result);

    return 0;
}

Solving Approach

 

 

 

Upvote
Downvote
Loading...

Input

5 10 25 5 30 15

Expected Output

30