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?
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
Is the min() function considered to be O(1) in python?
Yeah min() is O(n). But the problem's test cases are not strict enough to expose the inefficient algorithm. Python also adds another dimension because its builtin methods are often a lot faster than what you could write in pure python. I think that makes it easier to get away with a suboptimal algorithm. More on reddit.com
🌐 r/leetcode
3
1
May 2, 2023
python - Time complexity of max function - Stack Overflow
How can I find the time complexity of this function: def f(lst, d, u): # assume 0 More on stackoverflow.com
🌐 stackoverflow.com
algorithm - Big O of min and max in Python - Stack Overflow
Of course, Python min and max have O(n) too: docs. You can write your own min/max function with a for loop and it will have the same complexity, but will be slower because it is not optimized in C. More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 - So, it has a space complexity of O(1), where 1 signifies a constant relationship between running this algorithm and the additional memory this algorithm needs. You might notice that the algorithm creates a temporary variable num to store each number in the input array. But this variable also gets reassigned constantly in each for loop and its size never grows. Python max() function can return the maximum value of an iterable or iterables, as long as they are of the same data type.
🌐
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 › 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.
🌐
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.

🌐
Python Pool
pythonpool.com › home › blog › using python max function like a pro | python max()
Using Python Max Function Like a Pro | Python max() - Python Pool
June 14, 2021 - ... The time complexity of the python max function is O(n). Unlike max functions in other programming languages like C++, it offers a variety of uses. We can apply it on the string, which is not possible in other languages.
Find elsewhere
🌐
AlgoCademy
algocademy.com › link
Max In Array in Python | AlgoCademy
def find_max_value(nums): # Check ...value(nums)) # Output: 11 · The time complexity of this approach is O(n), where n is the number of elements in the array....
🌐
Python Reference
python-reference.readthedocs.io › en › latest › docs › functions › max.html
max — Python Reference (The Right Way) 0.1 documentation
Optional. Specifies a one-argument ordering function; must be in keyword form. ... When comparing sequences lexical comparison is used. >>> max(1, 2, 3) 3 >>> max('A', 'a', 'b') 'b' >>> max([1, 2], [2, 1], [3, 1]) [3, 1] >>> max(str([1, 2]), str([2, 1]), str([3, 1])) '[3, 1]'
🌐
GitHub
gist.github.com › yvan-sraka › 52384523a92bb0910d770f0fdde59bbd
Max function implementation explained in Python · GitHub
if list[0] > rec_max(list[1:]): # Calling here once return list[0] else: ''' Calling here again, which will lead to recurse the function it already computed the value for. This will impact the time complexity of the function majorly for large lists. ''' return rec_max(list[1:]) Instead of that, we can write it as below ·
🌐
Quora
quora.com › What-is-the-best-algorithm-for-finding-the-max-in-an-array-and-what-is-its-complexity
What is the best algorithm for finding the max in an array and what is its complexity? - Quora
Answer (1 of 7): As it needs traversal of all of the array. Without checking all of the elements, min|max can't be find out. So worst case is O(n) Best is constant time
🌐
Stack Overflow
stackoverflow.com › questions › 63823714 › time-complexity-of-max-function
python - Time complexity of max function - Stack Overflow
def 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)) What this function does is find the largest value which appears twice in the list in the range between d and u ... @bendaMan Very sure. Each time you increase u-d by one, you double the number of calls.
🌐
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 -
🌐
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 - In this Python program example, the max() function compares the floating-point numbers and returns 3.14 as the highest value. In Python, an iterable is any object that can return its elements one at a time, such as strings, dictionaries, sets, lists, and tuples.
🌐
After Academy
afteracademy.com › blog › find-the-minimum-and-maximum-value
Find minimum and maximum value in an array - Interview Problem
October 6, 2019 - How is the space complexity derived to be O(logn)? Why there are 2 base cases? What if we remove the base case with array size 2? Why prefer mid = start + (end - start)/2 over (start + end)/2 when calculating middle of the array ? Can the number of comparisons be decreased further? In this approach, we pick array elements in pairs and update the min and max.
🌐
UCI
ics.uci.edu › ~pattis › ICS-33 › lectures › complexitypython.txt
Complexity of Python Operations
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) ) If we repeat an O(f(N)) process O(N) times, the resulting complexity class is O(N)*O(f(N)) = O( N*f(N) ). ...
🌐
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.
🌐
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...