2
\$\begingroup\$

I wanted to ask for a code review for the following interview question:

Problem: Max Gain

Given an list of integers, write a method - max_gain - that returns the maximum gain. Maximum Gain is defined as the maximum difference between 2 elements in a list such that the larger element appears after the smaller element. If no gain is possible, return 0.

Example:

max_gain([100,40,20,10]) ==> 0
max_gain([0,50,10,100,30]) ==> 100

Solution

def max_gain(input_list):
    if len(input_list) < 2:
        return 0
    a = input_list[0]
    max_val = 0
    for i in input_list[1:]:
        max_val = max(max_val, i-a)
        a = min(a, i)
    return max_val
\$\endgroup\$
0

2 Answers 2

2
\$\begingroup\$

As a variable name, i has a connotation of being an index, rather than a value, of a list. I would expect it to be used in contexts more like for i, value in enumerate(values).

Making the slice input_list[1:] would involve duplicating most of the list. I would use an iterator to avoid doing that, and also to simplify the handling of the special case.

With a few improvements in naming…

def max_gain(input_list):
    prices = iter(input_list)
    best_buy = next(prices, 0)
    profit = 0
    for price in prices:
        profit = max(profit, price - best_buy)
        best_buy = min(best_buy, price)
    return profit
\$\endgroup\$
0
\$\begingroup\$

The code logic is sound. I do not think you can optimise it further. Though, you should add the docstring to the function, and use better variable names (current_min instead of a for eg.).

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.