Tutorialspoint
Problem
Solution
Submissions

Largest Element in an Array

Certification: Basic Level Accuracy: 85.71% Submissions: 7 Points: 5

Write a C# program to find the largest element in a given integer array.

Example 1
  • Input: nums = [5, 3, 8, 1]
  • Output: 8
  • Explanation:
    • Step 1: Initialize a variable max with the first element of the array (5).
    • Step 2: Iterate through the array [5, 3, 8, 1].
    • Step 3: Compare each element with max and update if the current element is larger.
    • Step 4: When we reach 8, update max = 8 since 8 > 5.
    • Step 5: After completing the iteration, return max which is 8.
Example 2
  • Input: nums = [-10, -5, -3, -1]
  • Output: -1
  • Explanation:
    • Step 1: Initialize a variable max with the first element of the array (-10).
    • Step 2: Iterate through the array [-10, -5, -3, -1].
    • Step 3: Compare each element with max and update if the current element is larger.
    • Step 4: When we reach -5, update max = -5 since -5 > -10.
    • Step 5: When we reach -3, update max = -3 since -3 > -5.
    • Step 6: When we reach -1, update max = -1 since -1 > -3.
    • Step 7: After completing the iteration, return max which is -1.
Constraints
  • 1 ≤ array length ≤ 10^5
  • -10^9 ≤ array elements ≤ 10^9
  • Time Complexity: O(n) (Single pass through the array)
  • Space Complexity: O(1)
ArraysData StructureWiproTech Mahindra
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Initialize Max: Start with the first element as the initial maximum.
  • Iterate: Loop through the array and update the max value whenever a larger element is found.
  • Edge Case: Handle arrays with a single element.
  • Return Result: At the end of the loop, return the maximum value.

Submitted Code :