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
🌐
Stack Overflow
stackoverflow.com › questions › 63823714 › time-complexity-of-max-function
python - Time complexity of max function - Stack Overflow
How can I find the time complexity of this function: Copydef f(lst, d, u): # assume 0<=d<=u<n where n is the length of the list if lst[d] == lst[u]: return u-d return max(f(lst, d+1, u), f(lst, d, u-1))
Top answer
1 of 2
25

It requires more careful analysis, such as you'll find here. The basic insight is that only the root of the heap actually has depth log2(len(a)). Down at the nodes one above a leaf - where half the nodes live - a leaf is hit on the first inner-loop iteration.

"Exact" derivation

Waving hands some, when the algorithm is looking at a node at the root of a subtree with N elements, there are about N/2 elements in each subtree, and then it takes work proportional to log(N) to merge the root and those sub-heaps into a single heap. So the total time T(N) required is about

T(N) = 2*T(N/2) + O(log(N))

That's an uncommon recurrence. The Akra–Bazzi method can be used to deduce that it's O(N), though.

I think more informative, and certainly more satifsying, is to derive an exact solution from scratch. Toward that end, I'll only talk about complete binary trees: as full as possible on every level. Then there 2**N - 1 elements in total, and all subtrees are also complete binary trees. This sidesteps mounds of pointless details about how to proceed when things aren't exactly balanced.

When we're looking at a subtree with 2**k - 1 elements, its two subtrees have exactly 2**(k-1) - 1 elements each, and there are k levels. For example, for a tree with 7 elements, there's 1 element at the root, 2 elements on the second level, and 4 on the third. After the subtrees are heapified, the root has to moved into place, moving it down 0, 1, or 2 levels. This requires doing comparisons between levels 0 and 1, and possibly also between levels 1 and 2 (if the root needs to move down), but no more that that: the work required is proportional to k-1. In all, then,

T(2**k - 1) = 2 * T(2**(k-1) - 1) + (k - 1)*C

for some constant C bounding the worst case for comparing elements at a pair of adjacent levels.

What about T(1)? That's free! A tree with only 1 element is a already a heap - there's nothing to do.

T(1) = 0

One level above those leaves, trees have 3 elements. It costs (no more than) C to move the smallest (for a min-heap; largest for a max-heap) to the top.

T(3) = C

One level above that trees have 7 elements. It costs T(3) to heapify each of the subtrees, and then no more than 2*C to move the root into place:

T(7) = 2*C + 2*C = 4*C

Continuing in the same way:

T(15) = 2* 4*C + 3*C = 11*C
T(31) = 2*11*C + 4*C = 26*C
T(63) = 2*26*C + 5*C = 57*C
...
T(2**k - 1) = (2**k - k - 1)*C

where the last line is a guess at the general form. You can verify that "it works" for all the specific lines before it, and then it's straightforward to prove it by induction.

So, where N = 2**k - 1,

T(N) = (N - log2(N+1)) * C

which shows that T(N) is bounded above by C*N, so is certainly O(N).

2 of 2
0

For more mathy folks: Consider a complete binary tree with L levels, labeled from 0 (root) to L-1. Such a tree has N=2^L-1 nodes. Conversely, a complete binary tree with N nodes has L=log2(N-1) levels.

For any given node at a level l, the bubble/heapify down operation makes L-1-l comparisons. For the total number of operations, we thus need to compute the sum:

which is equal to

Note: strictly speaking, the sum goes from 0 to L-2, as the leaves are not to be operated on. However, L-(L-1)-1 is zero, so we can leave the sum upper limit to be L-1

🌐
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 - We will build the stack from scratch and try to write a helper method for the stack which can fetch the Maximum element of the Stack. So we are allowed to use O(N) extra memory but we have to fetch the item in constant Time complexity of O(1). If you are reading this article for first time you can refer to my earlier article on Stack in python as below -
Find elsewhere
🌐
AlgoMonster
algo.monster › home › 716. max stack
716. Max Stack - In-Depth Explanation
Why this fails: When multiple elements ... maximum (closest to top), but with only values, you'd have to traverse the entire stack to find it, breaking the O(log n) time complexity requirement....
🌐
Stack Overflow
stackoverflow.com › questions › 79976302 › time-complexity-python
arrays - time complexity ~~ python - Stack Overflow
Find the maximum subarray sum (Kadane's Problem) in an array containing negative numbers. Brute force is O(n²)/O(n³) — optimize to O(n). Find all pairs in an array that sum to a target value (retur...
🌐
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.
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › time-and-space-complexity-analysis-of-stack-operations
Time and Space Complexity analysis of Stack operations - GeeksforGeeks
July 23, 2025 - # Python program for above approach class Stack: def __init__(self): self.stack = [None]*10 self.MAX = 10 self.top = -1 def push(self, val): # If top is pointing to maximum size of stack if self.top >= self.MAX-1: # Stack is full print('Stack Overflow') return # Point top to new top self.top += 1 # Insert new element at top of stack self.stack[self.top] = val print(val, 'pushed into stack successfully !') # Stack is already empty def pop(self): if self.top < 0: print('Stack Underflow') else: # Removing top of stack x = self.stack[self.top] self.top -= 1 print('Element popped from stack:', x) st = Stack() st.push(1) st.pop() st.pop() # This code is contributed by adityamaharshi21
🌐
Pythoncomplexity
pythoncomplexity.com › builtins › max
Maximum - Python Big-O: Time & Space Complexity
# O(n) - must scan all items numbers = [3, 1, 4, 1, 5, 9, 2, 6] max_val = max(numbers) # 9 # O(n) for any iterable max_val = max([1, 2, 3]) # 3 max_val = max((1, 2, 3)) # 3 max_val = max({1, 2, 3}) # 3 max_val = max("abc") # 'c'
🌐
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 the correct result. This remains true regardless of whether values are numbers, strings, or custom objects with comparison methods.
🌐
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).
🌐
Stack Overflow
stackoverflow.com › questions › 47826052 › python-maxtransform-reduce-time-complexity
loops - python maxTransform reduce time complexity - Stack Overflow
December 15, 2017 - sa = maxTransform(A) #debug print ('sa = {} '.format(sa)) #debug -ends ssa = maxTransform(sa) #debug print ('ssa = {} '.format(ssa)) #debug -ends return sum(ssa)%(10**9+7) def maxTransform(a): b=[] lenA = len(a) for k in range(0, len(a)): for i in range(0, len(a)-k): j=i+k #debug print ('k = {}, i={}, j = {}, a = {} '.format(k, i, j, max(a[i:j+1]))) #debug -ends b.append(max(a[i:j+1])) #for i -ends #for k -ends return b if __name__ == "__main__": n = int(raw_input().strip()) a = map(int, raw_input().strip().split(' ')) result = solve(a) print result · Right now its time complexity is O(n^2).
🌐
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.