Find and print the maximum value in { 3, 7, 2, 9, 1 }.
Ready — edit the code above and click Run.
using System;
class Program
{
static void Main()
{
int[] arr = { 3, 7, 2, 9, 1 };
int max = arr[0];
foreach (var x in arr)
if (x > max) max = x;
Console.WriteLine(max);
}
}
Try solving on your own first, then reveal the official answer.
Track running max—O(n) time, O(1) space. Classic array interview question.