Given an array of integers, return the maximum value from the array.
Example:
Input: nums = [2, 7, 11, 8, 11, 8, 3, 11]
Output: 11
Explanation: The maximum value is 11
Note:
Do not use builtin functions such as max()
, it would defy the purpose of the challenge. Write the whole code yourself.
The core challenge of this problem is to find the maximum value in an array without using built-in functions. This is a fundamental problem in computer science and is often used to teach basic algorithmic thinking and iteration techniques.
Common applications include finding the highest score in a game, the maximum temperature in a dataset, or the largest financial transaction in a list.
Potential pitfalls include not handling empty arrays or arrays with all negative numbers correctly.
To solve this problem, we can iterate through the array and keep track of the maximum value encountered so far. This approach ensures that we only pass through the array once, making it efficient.
Let's break down the approach:
Here is a step-by-step breakdown of the algorithm:
max_value
to INT_MIN
(the smallest possible integer).num
in the array nums
.num
is greater than max_value
, update max_value
to num
.max_value
.#include <iostream>
#include <vector>
#include <climits> // For INT_MIN
// Function to find the maximum value in an array
int findMaxValue(const std::vector<int>& nums) {
// Initialize max_value to the smallest possible integer
int max_value = INT_MIN;
// Iterate through each element in the array
for (int num : nums) {
// Update max_value if the current element is greater
if (num > max_value) {
max_value = num;
}
}
// Return the maximum value found
return max_value;
}
int main() {
// Example usage
std::vector<int> nums = {2, 7, 11, 8, 11, 8, 3, 11};
std::cout << "The maximum value is: " << findMaxValue(nums) << std::endl;
return 0;
}
The time complexity of this approach is O(n)
, where n
is the number of elements in the array. This is because we only make a single pass through the array.
The space complexity is O(1)
since we are using a constant amount of extra space regardless of the input size.
Consider the following edge cases:
To test the solution comprehensively, consider the following test cases:
[2, 7, 11, 8, 11, 8, 3, 11]
[]
[-5, -1, -3, -4]
[7, 7, 7, 7]
[42]
When approaching such problems, consider the following tips:
Finding the maximum value in an array is a fundamental problem that helps build a strong foundation in algorithmic thinking. By understanding and implementing this solution, you can tackle more complex problems with confidence.
Remember to practice regularly and explore different approaches to enhance your problem-solving skills.
For further reading and practice, consider the following resources: