Easy–medium · arrays

Maximum in an Array

Read N, then N numbers, and print the largest. Takes the running-maximum idea from Maximum of Three and scales it to any count — the exact shape of a thousand future problems.

At a glanceRead N numbers into an array and keep a running maximum seeded from the first element — seeding it with 0 breaks on an all-negative array.

Problem

Input: first line has N (1 ≤ N ≤ 1000); second line has N integers.

Output: the largest of them.

Samples:

InputOutput
5
3 9 1 7 4
9
4
-3 -7 -1 -9
-1

Your solution

main.cpp — your solution
Custom input for "Run my input"

Judging runs in your browser against hidden tests. A runaway loop is cut off after 3 seconds — still, make sure every loop has an exit. Your code is saved in this browser as you type.

Stuck? Hints

Hint 1 — two valid architectures

Option A: read everything into int a[1000], then loop to find the max. Option B: no array at all — keep a running max while reading (cin >> a; inside the loop). Both pass; B uses O(1) memory. Knowing when you don't need to store data is a real algorithmic skill.

Hint 2 — seeding the maximum

Seed with the first value, never with 0 — the judge includes all-negative inputs where a 0 seed reports a number that was never in the data. (Same trap as Maximum of Three, now with room to bite harder.)

Solution (try it first!)
#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int m, a;
    cin >> m;                 // first value seeds the maximum
    for (int i = 1; i < n; i++) {
        cin >> a;
        if (a > m) m = a;
    }
    cout << m << endl;
    return 0;
}

Stretch goals: print the max's position (remember the index when you update), or the min and max, or the sum and average — careful, average hits the integer-division trap. Next level: Binary Representation.

Deep dive

Why this works

A running maximum over a stream needs O(1) memory. You never need to keep the array — that is the insight interviewers look for.

The cost

O(n) time, O(1) extra space, even though the input is O(n).

Where it goes wrong

  • Declaring a fixed 100-slot array when the problem allows 1,000 is a stack overflow waiting to happen. Stream when you can.
  • Tracking the position needs a second variable; forgetting to update it gives the value but not the index.

Next step

Count instead of compare: Even and Odd Count.

Two things to remember

  • A running best needs no array.
  • O(n) time does not require O(n) memory.
🐞 This version fails — open it and try

Seeds the maximum with 0 instead of the first element

#include <iostream>
using namespace std;

int main() {
    int n;
    cin >> n;
    int best = 0;
    for (int i = 0; i < n; i++) {
        int v;
        cin >> v;
        if (v > best) best = v;
    }
    cout << best << endl;
    return 0;
}