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
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jan 21, 2018 at 17:44
\$\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
answered Jan 23, 2018 at 5:41
\$\endgroup\$
1
\$\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.).

answered Jan 23, 2018 at 3:51
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.