โจทย์
Return the largest value in the list by checking each element once.
Implement array_maximum(numbers).
Input
numbers: A non-empty list of integers.
Output
Return the maximum.
เงื่อนไข
1 ≤ length ≤ 100,000
ตัวอย่าง
อินพุต:
numbers = [3, 9, 2]
ผลลัพธ์ที่คาดหวัง:
expected = 9
อินพุต:
std::vector<long long> numbers = {3, 9, 2};
ผลลัพธ์ที่คาดหวัง:
long long expected = 9;
อินพุต:
long[] numbers = new long[] {3, 9, 2};
ผลลัพธ์ที่คาดหวัง:
long expected = 9;
คำอธิบาย
9 is larger than 3 and 2.
อินพุต:
numbers = [-4, -1, -7]
ผลลัพธ์ที่คาดหวัง:
expected = -1
อินพุต:
std::vector<long long> numbers = {-4, -1, -7};
ผลลัพธ์ที่คาดหวัง:
long long expected = -1;
อินพุต:
long[] numbers = new long[] {-4, -1, -7};
ผลลัพธ์ที่คาดหวัง:
long expected = -1;
คำอธิบาย
With only negative values, -1 is the largest.
แนวทางการแก้
ลองทำเองก่อน แล้วค่อยเปิดคำใบ้ทีละข้อ
คำใบ้ 1
Start with the first element as the best value so far.
คำใบ้ 2
Scan the list once and update the best value whenever you find a larger one.
คำใบ้ 3
Do not assume values are positive; negatives can still be the maximum.
ความซับซ้อนที่คาดหวัง
O(n) time, O(1) extra space
แหล่งอ้างอิง
โจทย์นี้ปรับให้เหมาะกับ CodeUtility กรุณาทำตามคำชี้แจงและข้อจำกัดด้านบน