Problem Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
Best Time to Buy and Sell Stock - LeetCode
Can you solve this real interview question? 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 choosin
leetcode.com
Solution 1. Two Pointer
Time: $O(N)$
Space: $O(1)$
class Solution(object):
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
buy = 0; sell = 1
max_profit = 0
for sell, price in enumerate(prices):
profit = price - prices[buy]
if profit < 0:
buy = sell
else:
max_profit = max(max_profit, profit)
return max_profit
'Problem Solving' 카테고리의 다른 글
[Leetcode] 226. Invert Binary Tree (0) | 2023.07.13 |
---|---|
[Leetcode] 125. Valid Palindrome (0) | 2023.07.12 |
[Leetcode] 20. Valid Parentheses (0) | 2023.07.11 |
[Leetcode] 167. Two Sum II - Input Array Is Sorted (0) | 2023.07.11 |
[Leetcode] 1. Two Sum (0) | 2023.07.11 |