# [Best time to buy and sell stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/) ###### tags: `Leetcode`, `Easy`, `Sliding Window` ## Approach * Initialize `maximum_profit` to 0 and `cost_price` to value at 0<sup>th</sup> index * Iterate from 1<sup>st</sup> index to the end of the input list * Check if current value is greater than the `cost_price` * Calculate profit `current_value - cost_price` * Calculate maximum of `maximum_profit` and `profit` * Otherwise set `cost_price` to the value at current index ## Asymptotic Analysis ### Time Complexity: **O(N)** ### Space Complexity: **O(1)** ## Code ``` python from typing import List class BestTimeToBuyAndSellStock: @staticmethod def max_profit(prices: List[int]) -> int: cost_price, maximum_profit = prices[0], 0 for index in range(1, len(prices)): if prices[index] > cost_price: profit = prices[index] - cost_price maximum_profit = max(maximum_profit, profit) else: cost_price = prices[index] return maximum_profit nums = [7, 6, 4, 3, 1] nums1 = [7, 1, 5, 3, 6, 4] print(BestTimeToBuyAndSellStock.max_profit(nums)) print(BestTimeToBuyAndSellStock.max_profit(nums1)) ```