728x90
반응형
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/description/
문제
문제 분석
1. 가장 작은 값을 계속 갱신해가며 profit을 구하면 됩니다. 배열 순서대로 진행하면 이전의 결과와 차이를 계산하지 않고 계속 배열 뒤쪽의 값들과만 계산할 수 있습니다.
풀이
class Solution {
public:
int maxProfit(vector<int>& prices) {
int min = 10000;
int profit = 0;
for(const auto& price: prices){
if(price < min){
min = price;
}
int temp = price - min;
if(profit < temp){
profit = temp;
}
}
return profit;
}
};
728x90
반응형
'Problem Solving > LeetCode' 카테고리의 다른 글
[LeetCode] C++ 21. Merge Two Sorted Lists (0) | 2024.08.16 |
---|---|
[LeetCode] C++ 234. Palindrome Linked List (0) | 2024.08.16 |
[LeetCode] C++ 238. Product of Array Except Self (0) | 2024.08.16 |
[LeetCode] C++ 561. Array Partition I (0) | 2024.08.15 |
[LeetCode] C++ 15. 3Sum (0) | 2024.08.15 |