121. Best time to buy and sell stock

https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

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.

Example 1: Input: [7,1,5,3,6,4] Output: 5 Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.


  • code
class Solution {
    public int maxProfit(int[] prices) {
        int res = 0, last = prices[0], cur = 0;
        for (int i = 1; i < prices.length; i++){
            cur += prices[i] - prices[i-1];
            if (cur < 0){
                cur = 0;
                continue;
            }
            res = Math.max(cur, res);
        }
        return res;
    }
}
  • code
public class Solution {
    public int maxProfit(int prices[]) {
        int minprice = Integer.MAX_VALUE;
        int maxprofit = 0;
        for (int i = 0; i < prices.length; i++) {
            if (prices[i] < minprice)
                minprice = prices[i];
            else if (prices[i] - minprice > maxprofit)
                maxprofit = prices[i] - minprice;
        }
        return maxprofit;
    }
}
  • code
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        cur = res = 0
        for i in range(1, len(prices)):
            cur += prices[i] - prices[i-1]
            if cur < 0: cur = 0
            res = max(res, cur)
        return res
  • code
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        minday = prices[0]
        maxprofit = 0
        for v in prices:
            if v < minday:
                minday = v
            else:
                maxprofit = max(maxprofit, v - minday)

        return maxprofit