# My 1 line Python solution

• The logic is pretty straight, we find all peaks and related bottom elements, then sum all peaks minus all bottoms.

``````class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
return sum([y for x, y, z in zip(prices[0:-1], prices[1:], prices[2:] + [prices[-1]]) if y > x and y >= z]) - sum([y for x, y, z in zip([prices[0]] + prices[0:-2], prices[0:-1], prices[1:]) if y <= x and y < z]) if len(prices) > 0 else 0
``````

UPDATE:

this version is more clear and simpler.

``````class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
return sum([y - x for x, y in zip(prices[:-1], prices[1:]) if x < y])``````

• prices[0:-1] could be simly prices[:-1]

• Yes, thanks. Already update the solution.

• You can remove '[ ]' in sum
Try:
sum(y - x for x, y in zip(prices[:-1], prices[1:]) if x < y)

This will give you a generator.

• ``````class Solution:
# @param {integer[]} prices
# @return {integer}
def maxProfit(self, prices):
return sum(y-x for x, y in zip(prices[:-1], prices[1:]) if y > x)
``````

This one version is even simpler.
You don't need to generate a list then get the sum. It can be processed through generator.

• The algorithm is very concise. I like it very much. My code is:
class Solution:
# @param {integer[]} prices
# @return {integer}
def maxProfit(self, prices):
if prices is None:
return 0

``````    if len(prices)<1:
return 0

pr_max = 0
pr_old = prices[0]
for pr in prices:
if pr > pr_old:
pr_max += (pr-pr_old)
pr_old = pr
else:
pr_old = pr

return pr_max
``````

Clearly, my coding style is affected by C/C++. In my opinion, your updated code can be seen as a pure python style. Especially, the advanced feature of python, generator is employed

• I guess the solution below using no zip() is more concise and simple to understand:

``````class Solution:
# @param {integer[]} prices
# @return {integer}
def maxProfit(self, prices):
return sum([max(prices[i+1] - prices[i],0) for i in range(len(prices)-1)])``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.