Problem
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
Algorithm
Calculate from the end to the head. Save the max-value until i-th day and then find the max profit in each day.
Code
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if not prices:
return 0
prices_len = len(prices)
index = prices_len-1
max_p = prices[index]
ans = 0
while index >= 0:
profit = max_p - prices[index]
if ans < profit:
ans = profit
if max_p < prices[index]:
max_p = prices[index]
index -= 1
return ans