C++ bootcamp · Lab 16

Maximum in a vector

mediumVectors12 minLesson: Vectors

Read the question, write C++ on the right, then Run or Check.

QuestionHint and solution stay closed until you open them

The first number is n, then n integers follow. Print the maximum.

std::max_element returns an iterator — dereference it with * to get the value.

Input. n, then n integers (whitespace-separated).

Output. One integer: the maximum.

Constraints

  • 1 ≤ n ≤ 1000

Examples

Example 1
Input
5
3 1 8 2 4
Output
8
Example 2
Input
1
42
Output
42
Hint
  1. std::vector<int> nums(n); then read each element in a loop.
  2. *std::max_element(nums.begin(), nums.end()) gives the largest.
Show correct code

Peek only after you have tried. You can still Check your own version.

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
  int n;
  std::cin >> n;
  std::vector<int> nums(n);
  for (int i = 0; i < n; i++) std::cin >> nums[i];
  std::cout << *std::max_element(nums.begin(), nums.end()) << "\n";
  return 0;
}
main.cppC++17 · g++ · Ctrl + Enter runs
ResultIdle
Run to see output. Check grades the tests.