β Back to Revisions
Day 3
View Problem βMax Element in Array
π
October 25, 2025π·οΈ Smart Interviews
Complexity Analysis
Brute Force
N/A
Optimized
N/A
Space
N/A
Solutions
Pythonπ
import sys
def solve_max_element():
try:
# Read the entire line of array elements
nums = list(map(int, sys.stdin.readline().split()))
except:
return
if not nums:
return
# Initialize max_val to the first element
max_val = nums[0]
# Linear scan (O(N))
for num in nums[1:]:
if num > max_val:
max_val = num
print(max_val)
if __name__ == "__main__":
solve_max_element()C++β‘
#include <iostream>
#include <vector>
#include <algorithm> // Required for std::max or std::max_element
#include <limits> // Required for numeric_limits
using namespace std;
void solve_max_element() {
int N;
// Read N (the number of elements in the array)
if (!(cin >> N)) return;
// Read the array elements
vector<int> nums(N);
for (int i = 0; i < N; ++i) {
if (!(cin >> nums[i])) return;
}
if (N == 0) return;
// Linear Scan (O(N) Time, O(1) Extra Space)
// Initialize max_val to the smallest possible integer value
// to handle cases where array elements are negative.
int max_val = numeric_limits<int>::min();
for (int num : nums) {
if (num > max_val) {
max_val = num;
}
}
// Alternative: Use STL max_element (also O(N))
// int max_val = *max_element(nums.begin(), nums.end());
cout << max_val << endl;
}
int main() {
// Note: Input reading style may vary based on platform
solve_max_element();
return 0;
}Tags
arraytraversalsimple-scan
π‘ Revision Tips
- β’ Try solving from memory before checking your solution
- β’ Focus on the approach and pattern, not just the code
- β’ Can you explain the solution to someone else?
- β’ Try implementing in a different language