// Challenge: find the largest number in a list.
// Input: [3, 7, 2, 9, 4]
// Expected output: 9
// Solution 1: iterating and keeping the largest seen so far.
// An interview classic to show you know how to loop and compare.
int maxWithLoop(List<int> numbers) {
if (numbers.isEmpty) {
throw ArgumentError('The list cannot be empty');
}
var largest = numbers[0];
for (final number in numbers) {
if (number > largest) {
largest = number;
}
}
return largest;
}
// Solution 2: using reduce, more idiomatic in Dart.
// reduce combines the elements two at a time with the given function.
int maxWithReduce(List<int> numbers) {
return numbers.reduce((a, b) => a > b ? a : b);
}
void main() {
print(maxWithLoop([3, 7, 2, 9, 4])); // 9
print(maxWithReduce([3, 7, 2, 9, 4])); // 9
print(maxWithLoop([-5, -1, -10])); // -1 (works with negatives)
print(maxWithReduce([42])); // 42 (a single element)
// Explanation:
// The loop version starts by assuming the first element is the
// largest and keeps updating it. The reduce version does the same, but
// lets Dart walk through the list: it compares two at a time and keeps
// the larger one. Watch out for the empty list: reduce would throw an
// error, which is why in the manual version we validate first.
}