It's O(n), since it must check every element. If you want better performance for max, you can use the heapq module. However, you have to negate each value, since heapq provides a min heap. Inserting an element into a heap is O(log n).

Answer from Matthew Flaschen on Stack Overflow
Discussions

How to Compute Max Value with Linear Time Complexity When 'k' Is Not Fixed?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
4
0
January 28, 2024
What is the time complexity of the Python code below? Problem description and code provided. def max_independent_set(nums): #function dp=[0 for i in range(len(nums))] #create a dp table to find the max sum at index i
Example 1: Input: (7,2,5,8,6] Output: ... problem using dynamic Programming. Name your function max_independent_set(nums). Name your file MaxSet.py b. What is the time complexity of your implementation?... More on chegg.com
🌐 chegg.com
1
April 13, 2022
How to Compute Max Value with Linear Time Complexity When 'k' Is Not Fixed?
This is also known as the range minimum query problem (or RMQ for short). You can split it by how long it takes to pre-process and how long it takes to answer a query. It looks like you want something that's O(n) pre-processing and O(1) query. There are a variety of approaches listed here: https://cp-algorithms.com/sequences/rmq.html I think the simplest one to understand that's linear time pre-processing and faster than O(log n) per query is this one: https://cp-algorithms.com/data_structures/disjoint_set_union.html#arpa . The optimal time complexity one is this: https://cp-algorithms.com/graph/lca_farachcoltonbender.html , but is much more complicated to implement. More on reddit.com
🌐 r/algorithms
6
10
January 28, 2024
Time-complexity of this algo?
.count(x) means 'count all the objects in the sequence equal to x'. This is O(n) by definition, as the amount of items to process is always the length of the sequence. Meaning that if the sequence would be 10 times longer, it would need to count 10 times as many items. .max(sequence) means 'check all objects in the sequence and return the highest'. Also O(n) as there is no other option but to traverse the entire sequence, the same 10-fold example applies. Thus effectively doing both in a run is O(2n)*. This doesn't boil down to the 'efficiency' of each function, it's that both don't allow to be less or more efficient as they literally mean to check for something that needs all objects in a sequence to be checked, it's your combination that makes it inefficient. You then need to perform a custom method if you want to approach this in one iteration def count_max(seq): cur_max = seq[0] max_count = 1 for item in seq[1:]: if item > cur_max: cur_max = item max_count = 1 elif item == cur_max: max_count += 1 return max_count # then in your algo for q in query: answers.append(max_count(price[q-1:]) then another thing is to consider how exactly you are executing this for the price sequence. If you are repeating this for every object in price but just shifted one index (as query is like [1, 2, 3, 4 etc]) then you could also consider implementing this better instead of repeating the count_max step over and over again for a smaller slice of price. But I can only guess because you don't explain the background here. *: technically speaking O(2n) equals O(n) as O is in regard to complexity, not time duration. More on reddit.com
🌐 r/learnpython
12
6
May 22, 2019
🌐
Python
wiki.python.org › moin › TimeComplexity
TimeComplexity - Python Wiki
[3] = For these operations, the worst case n is the maximum size the container ever achieved, rather than just the current size.
🌐
Pythoncomplexity
pythoncomplexity.com › builtins › max
Maximum - Python Big-O: Time & Space Complexity
# O(n*k) - evaluates key for each item words = ["apple", "pie", "cat"] longest = max(words, key=len) # O(n) - key is O(1) # More expensive key function numbers = [1, 2, 3, 4, 5] max_val = max(numbers, key=lambda x: expensive_function(x)) # O(n*k) where k = time for expensive_function · # O(n) - makes one pass through data lst = list(range(1000000)) result = max(lst) # ~1M comparisons # Same complexity with generators result = max(x**2 for x in range(10000)) # O(n)
🌐
Codemia
codemia.io › home › knowledge hub › big o of min and max in python
Big O of min and max in Python | Codemia
September 24, 2025 - The time complexity of Python's built-in min() and max() is generally O(n) for iterables, because each element must be examined at least once to guarantee...
🌐
Medium
medium.com › @lcao_5526 › 3-ways-to-find-the-largest-number-in-python-and-their-complexities-49f2a1e221ee
3 Ways to Find the Largest Number in Python and Their Complexities | by Lulu Cao | Medium
April 13, 2024 - In conclusion, the best solution to find the largest number in Python will be using a max() function, which has a time complexity of O(n) and a space complexity of O(1).
🌐
AlgoCademy
algocademy.com › link
Maximum Value in Array in Python (Time Complexity: O(n))
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 · The time complexity of this approach is O(n), where n is the number of elements in the array.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-maximum-record-value-key-in-dictionary
Python - Maximum record value key in dictionary - GeeksforGeeks
May 14, 2023 - The max() function is used to find the maximum value key, which has a time complexity of O(n log n) due to the use of a heap data structure.
🌐
GeeksforGeeks
geeksforgeeks.org › python › complexity-cheat-sheet-for-python-operations
Complexity Cheat Sheet for Python Operations - GeeksforGeeks
July 12, 2025 - Dictionaries in Python are implemented as hash tables, making them highly efficient for key-based operations. Here are the complexities: Note: Defaultdict has operations same as dict with same time complexity as it inherits from dict.
🌐
Reddit
reddit.com › r/learnprogramming › how to compute max value with linear time complexity when 'k' is not fixed?
r/learnprogramming on Reddit: How to Compute Max Value with Linear Time Complexity When 'k' Is Not Fixed?
January 28, 2024 -

Body: Hello! I'm stuck on a problem and could really use some fresh perspectives. I'm trying to figure out a linear time solution (`Theta(n)`) for a problem that's a bit tricky due to its varying parameters.

Here's the Challenge: Picture a line of creatures, each with its own strength and a unique ability. We have two lists: `x` for their strengths and `k` for the number of creatures in front of each (including itself) they can turn to for help.

Example to Illustrate: Let's say `x = [5, 10, 7, 2, 20]` and `k = [1, 2, 1, 3, 2]`. We need to find the maximum strength each creature can muster. For the fourth creature, it looks at the 3 creatures (`k[3] = 3`) - itself and the two creatures before it, considers the strengths `[10, 7, 2]`, and realizes it can leverage a maximum strength of `10`.

Our goal is to output a list where each element is this maximum accessible strength for each creature.

Where I'm Stuck: Here's my Python attempt so far:

def calculate_ output(x, k):
    output = []
    for i in range(len(x)):
        start_index = max(0, i - k[i])
        end_index = i + 1
        output.append(max(x[start_index:end_index]))
    return output

This isn't efficient. The nested iterations due to `max` make it O(n^2). For each creature, we slice and dice through the list based on `k`, which isn't ideal.

Looking for Advice: I'm hitting a wall here. Maybe there's a way to do this with a sliding window, but the variable range in `k` throws a wrench in the works. Any thoughts on data structures or algorithms to make this linear?

Thanks in advance! Looking forward to your insights.

🌐
Chegg
chegg.com › engineering › computer science › computer science questions and answers › what is the time complexity of the python code below? problem description and code provided. def max_independent_set(nums): #function dp=[0 for i in range(len(nums))] #create a dp table to find the max sum at index i
Solved What is the time complexity of the Python code | Chegg.com
April 13, 2022 - What is the time complexity of the Python code below? Problem description and code provided. def max_independent_set(nums): #function dp=[0 for i in range(len(nums))] #create a dp table to find the max sum at index i dp[0]=nums[0] #set first index with value of first element dp[1]=nums[1] #set first index with value of second element for i in range(2,len(nums)): #loop from second thrid index to last #store max of when either element is added to previous max or the max of the previous one or the element alone or the previous max alone dp[i]=max(nums[i],nums[i]+dp[i-2],dp[i-2],dp[i-1]) i=len(num
🌐
Reddit
reddit.com › r/algorithms › how to compute max value with linear time complexity when 'k' is not fixed?
r/algorithms on Reddit: How to Compute Max Value with Linear Time Complexity When 'k' Is Not Fixed?
January 28, 2024 -

Body: Hello! I'm stuck on a problem and could really use some fresh perspectives. I'm trying to figure out a linear time solution (`Theta(n)`) for a problem that's a bit tricky due to its varying parameters.

Here's the Challenge: Picture a line of creatures, each with its own strength and a unique ability. We have two lists: `x` for their strengths and `k` for the number of creatures in front of each (including itself) they can turn to for help.

Example to Illustrate: Let's say `x = [5, 10, 7, 2, 20]` and `k = [1, 2, 1, 3, 2]`. We need to find the maximum strength each creature can muster. For the fourth creature, it looks at the 3 creatures (`k[3] = 3`) - itself and the two creatures before it, considers the strengths `[10, 7, 2]`, and realizes it can leverage a maximum strength of `10`.

Our goal is to output a list where each element is this maximum accessible strength for each creature.

Where I'm Stuck: Here's my Python attempt so far:

def calculate_ output(x, k):
    output = []
    for i in range(len(x)):
        start_index = max(0, i - k[i])
        end_index = i + 1
        output.append(max(x[start_index:end_index]))
    return output

This isn't efficient. The nested iterations due to `max` make it O(n^2). For each creature, we slice and dice through the list based on `k`, which isn't ideal.

Looking for Advice: I'm hitting a wall here. Maybe there's a way to do this with a sliding window, but the variable range in `k` throws a wrench in the works. Any thoughts on data structures or algorithms to make this linear?

Thanks in advance! Looking forward to your insights.

🌐
Medium
medium.com › @khasnobis.sanjit890 › design-an-algorithm-that-can-return-the-maximum-item-of-a-stack-in-o-1-running-time-complexity-b312b9575d9c
Design an algorithm that can return the Maximum item of a stack in O(1) running time complexity. We can use O(N) extra memory! : Stack Again : Chapter 3 : In Python | by Sanjit Khasnobis | Medium
April 26, 2022 - Creating a Stack in python : Data Structure : Stack : Chapter 2 : In Python | by Sanjit Khasnobis | Apr, 2022 | Medium · Now without further delay let us first analyze the scenario. So we have to find the Maximum Number from Stack with O(1) time complexity.
🌐
UCI
ics.uci.edu › ~pattis › ICS-33 › lectures › complexitypython.txt
The Complexity of Python Operators/Functions
I prefer writing O(T) + max(O(B1),O(B2)) because it looks like what is happening: the test is always evaluated, and one of the blocks. ------------------------------------------------------------------------------ Law of Multiplcation for big-O notation O(f(n)) * O(g(n)) is O( f(n) * g(n) ) ...
🌐
Python Pool
pythonpool.com › home › tutorials › python max(): largest values, key, and default
Python max(): Largest Values, key, and default
July 13, 2026 - Use Python max() over iterables or arguments with key functions, default for empty inputs, tie behavior, and type checks.
🌐
Reddit
reddit.com › r/learnpython › time-complexity of this algo?
r/learnpython on Reddit: Time-complexity of this algo?
May 22, 2019 -

I was taking a Hackerrank test for employment screening and some of the test cases kept coming back with a timeout error, meaning that the code is running too slow. However, it runs perfectly fine in Pycharm.

I think this is no more than O(n), or maybe O(3N), but what am I not understanding here?

Follow up, what can I do to make this run faster? I wasn't sure if the max() and count() functions were terribly inefficient, so I implemented my own on the spot that I knew were definitely O(n) and still got the error on some test cases. I also tried storing the list slice as a variable once per iteration so it wouldn't have to re-slice the array.

def frequencyOfMaxValue(price, query):

answers = []

for q in query:

maximum = max(price[q-1:])

c = price[q-1:].count(maximum)

answers.append(c)

return answers

Edit:

Here's the problem.

price is an int array as is query. Each element in the query array specifies a starting index(indexes start at 1, rather than 0 which is odd but anyway) of the price array in which to search for count of the maximum element. The count of occurrences of the maximum element of the subarray is added to the return array, answers.

It seems my issue was iterating through the subarray of price once to find the max, then a second time to count the occurrences of the max.

Top answer
1 of 5
3
First of all, iyou have a slight misunderstanding of big O notation. O(3N) is not a thing, it is O(N). Big O does not predict how fast your algo runs, it predicts how it scales with input size. O(N) is basically saying “it runs in linesr time.” O(3N) thus doesn’t make too much sense. If it is timing out, there is likely a O(logN) solution or something. Please post the actual problem abd format your code so we can help you better.
2 of 5
2
.count(x) means 'count all the objects in the sequence equal to x'. This is O(n) by definition, as the amount of items to process is always the length of the sequence. Meaning that if the sequence would be 10 times longer, it would need to count 10 times as many items. .max(sequence) means 'check all objects in the sequence and return the highest'. Also O(n) as there is no other option but to traverse the entire sequence, the same 10-fold example applies. Thus effectively doing both in a run is O(2n)*. This doesn't boil down to the 'efficiency' of each function, it's that both don't allow to be less or more efficient as they literally mean to check for something that needs all objects in a sequence to be checked, it's your combination that makes it inefficient. You then need to perform a custom method if you want to approach this in one iteration def count_max(seq): cur_max = seq[0] max_count = 1 for item in seq[1:]: if item > cur_max: cur_max = item max_count = 1 elif item == cur_max: max_count += 1 return max_count # then in your algo for q in query: answers.append(max_count(price[q-1:]) then another thing is to consider how exactly you are executing this for the price sequence. If you are repeating this for every object in price but just shifted one index (as query is like [1, 2, 3, 4 etc]) then you could also consider implementing this better instead of repeating the count_max step over and over again for a smaller slice of price. But I can only guess because you don't explain the background here. *: technically speaking O(2n) equals O(n) as O is in regard to complexity, not time duration.
🌐
Unstop
unstop.com › home › blog › python max() function | all use cases with code examples
Python max() Function | All Use Cases With Code Examples
February 12, 2025 - Python max() function helps find the largest value among multiple objects or iterable items. Use the optional parameters key & default to customize its behavior.
🌐
Quora
quora.com › What-is-the-runtime-complexity-of-finding-the-maximum-value-in-an-array
What is the runtime complexity of finding the maximum value in an array? - Quora
Answer: Hello, Well, it will mainly depend on the content status of your array. If such content is sorted, you could have a complexity in O(1), since you just have to access to the last (or to the first, if item are sorted in inverted order) element. The access to that element will then, techn...
🌐
Facebook
facebook.com › groups › python › posts › 939972293510002
What algorithms do the python max() and min() functions ...
Popular groups · Find communities for you · Over 1 billion people across the globe are using Facebook Groups to explore their favorite topics · Log in · Categories · Science & tech · Travel · Animals · Sports & fitness · Entertainment
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › functions › max.html
max — Python Reference (The Right Way) 0.1 documentation
Returns the largest item in an iterable or the largest of two or more arguments · max (collection[, key])