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
출처: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/1589268914/
[해석]
- 당신에게 배열 prices가 주어집니다. 여기서 prices[i]는 i번째 날의 주식 가격입니다.
- 당신은 주식 한 개를 사는 단일 날짜와 그 주식을 파는 미래의 다른 날짜를 선택하여 이익을 최대화하고 싶습니다.
- 이 거래에서 얻을 수 있는 최대 이익을 반환하세요. 만약 이익을 얻을 수 없다면, 0을 반환하세요.
pseudo code
함수 maxProfit(prices[]):
// 엣지 케이스 처리
만약 prices의 길이가 1보다 작거나 같으면:
0 반환
// 변수 초기화
minPrice = 최대 정수 값 // 가능한 최소 구매 가격
maxProfit = 0 // 최대 이익
// 배열 순회
for i = 0부터 prices 길이-1까지:
// 더 낮은 구매 가격을 찾았을 경우
if prices[i] < minPrice:
minPrice = prices[i]
// 현재 판매 가격으로 더 큰 이익을 얻을 수 있는 경우
else if prices[i] - minPrice > maxProfit:
maxProfit = prices[i] - minPrice
maxProfit 반환
'【스터디노트】 > ▶알고리즘문제풀기' 카테고리의 다른 글
ValidPalindrome (0) | 2025.04.10 |
---|---|
[시간 복잡도] (0) | 2025.04.10 |
[Merge Two Sorted Lists] (0) | 2025.03.27 |
[Valid Parentheses] (0) | 2025.03.26 |
[twoSum] (0) | 2025.03.26 |