Start learning free

LESSON 145 OF 410 · LOOPS & GLOBAL VARIABLES

Maximum Value in Array in Python (Time Complexity: O(n))

Practice Read the full explanation

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.

STEP 1 OF 4
    Ctrl + Enter to check

    PYTHON · LOOPS & GLOBAL VARIABLES

    Max In Array in Python, explained

    Understanding the Problem

    The core challenge of this problem is to find the maximum value in an array without using built-in functions. This is a common problem in computer science and is fundamental for understanding array traversal and comparison operations.

    Common applications include finding the highest score in a game, the maximum temperature in a dataset, or the largest number in a list of financial transactions.

    Potential pitfalls include not handling empty arrays or arrays with all negative numbers correctly.

    Approach

    To solve this problem, we need to iterate through the array and keep track of the maximum value encountered so far. This approach ensures that we only traverse the array once, making it efficient.

    Let's break down the approach:

    • Initialize a variable to store the maximum value. Set it to the first element of the array.
    • Iterate through the array starting from the second element.
    • For each element, compare it with the current maximum value. If it is greater, update the maximum value.
    • After completing the iteration, the maximum value variable will hold the largest value in the array.

    Algorithm

    Here is a step-by-step breakdown of the algorithm:

    1. Initialize max_value to the first element of the array.
    2. Loop through the array starting from the second element.
    3. For each element, check if it is greater than max_value.
    4. If it is, update max_value.
    5. After the loop, return max_value.

    Code Implementation

    def find_max_value(nums):
        # Check if the array is empty
        if not nums:
            raise ValueError("The array is empty")
        
        # Initialize max_value with the first element of the array
        max_value = nums[0]
        
        # Iterate through the array starting from the second element
        for num in nums[1:]:
            # Update max_value if the current number is greater
            if num > max_value:
                max_value = num
        
        return max_value
    
    # Example usage
    nums = [2, 7, 11, 8, 11, 8, 3, 11]
    print(find_max_value(nums))  # Output: 11
    

    Complexity Analysis

    The time complexity of this approach is O(n), where n is the number of elements in the array. This is because we only traverse the array once.

    The space complexity is O(1) as we are using a constant amount of extra space.

    Edge Cases

    Consider the following edge cases:

    • An empty array: The function should raise an error or handle it gracefully.
    • An array with all negative numbers: The function should still return the maximum (least negative) number.
    • An array with a single element: The function should return that element.

    Examples:

    # Edge case: empty array
    try:
        print(find_max_value([]))  # Should raise an error
    except ValueError as e:
        print(e)  # Output: The array is empty
    
    # Edge case: single element array
    print(find_max_value([5]))  # Output: 5
    
    # Edge case: all negative numbers
    print(find_max_value([-1, -2, -3, -4]))  # Output: -1
    

    Testing

    To test the solution comprehensively, consider a variety of test cases:

    • Simple cases with positive numbers.
    • Cases with negative numbers.
    • Mixed positive and negative numbers.
    • Edge cases as discussed above.

    Example test cases:

    def test_find_max_value():
        assert find_max_value([2, 7, 11, 8, 11, 8, 3, 11]) == 11
        assert find_max_value([1, 2, 3, 4, 5]) == 5
        assert find_max_value([-1, -2, -3, -4]) == -1
        assert find_max_value([5]) == 5
        try:
            find_max_value([])
        except ValueError as e:
            assert str(e) == "The array is empty"
    
    test_find_max_value()
    print("All tests passed.")
    

    Thinking and Problem-Solving Tips

    When approaching such problems, consider the following tips:

    • Understand the problem requirements and constraints thoroughly.
    • Start with a simple, naive solution and then optimize it.
    • Think about edge cases and how your solution handles them.
    • Write clean, readable code with comments to explain your logic.
    • Practice similar problems to improve your problem-solving skills.

    Conclusion

    Finding the maximum value in an array is a fundamental problem that helps in understanding array traversal and comparison operations. By practicing such problems, you can improve your problem-solving skills and prepare for more complex challenges.

    Remember to consider edge cases and test your solution comprehensively to ensure its correctness.

    Additional Resources

    For further reading and practice, consider the following resources:

    Keep going with PythonAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free