https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Code
import sys class Solution(object): def maxProfit(self, prices): """ :type prices: List[int] :rtype: int """ min_price = sys.maxint max_profit = 0 for price in prices: min_price = min(min_price, price) max_profit = max(max_profit, price - min_price) return max_profit
Idea
`min_price` is the minimum price so far. The maximum profit must happen when `current price – min_price` is max.
Variant
If you are given difference array of prices, what would you do?
https://leetcode.com/discuss/48378/kadanes-algorithm-since-mentioned-about-interviewer-twists