-
Leetcode 121. Best Time to Buy and Sell Stock개발/Leetcode 2023. 6. 24. 10:51
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
문제
각 일자에 해당하는 가격의 정보가 담긴 배열 prices가 주어진다. 이 배열을 가지고 구매 일자 그리고 구매 일자 이후의 판매 일자를 통해 얻을 수 있는 최대의 이익을 반환하라
코드
class Solution:def maxProfit(self, prices: List[int]) -> int:profit = 0minPrice = max(prices)
for price in prices:if minPrice > price:minPrice = priceelif minPrice < price:profit = max(profit, price - minPrice)
return profitprices 배열을 순회하면서 최소 가격을 찾는다. 그와 동시에 최소가격을 가지고 최대의 이익을 얻을 수 있는 쌍을 찾아야 하는 문제이기에 최소가격과 현재 가격을 비교해 최대의 이익을 찾아 반환하는 코드
'개발 > Leetcode' 카테고리의 다른 글
Leetcode 125. Valid Palindrome (0) 2023.06.24 Leetcode 1232. Check If It Is a Straight Line (0) 2023.06.24 Leetcode 217. Contains Duplicate (0) 2023.06.24 Leetcode 714. Best Time to Buy and Sell Stock with Transaction Fee (0) 2023.06.22 [Leetcode] 1161. Maximum Level Sum of a Binary Tree (0) 2023.06.15