일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
- 깊이 우선 탐색
- Interval
- hash table
- LeetCode
- dynamic programming
- 이진탐색
- DFS
- 비트 조작
- bitwise operation
- union-find
- 탐욕알고리즘
- 배열
- 알고리즘
- CPP
- Sort
- C++
- graph
- 비트 연산
- Sorting
- binary
- binary search
- Array
- algorithm
- bit manipulation
- Depth-First Search
- unordered_map
- Greedy
- 동적계획법
- 메모이제이션
- linked list
- Today
- Total
공대생 공부노트(Notes for Engineering Studies)
[ leetcode 문제풀이 ] Best Time to Buy and Sell Stock 본문
[ leetcode 문제풀이 ] Best Time to Buy and Sell Stock
301동 노숙자 2022. 1. 30. 18:53https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Best Time to Buy and Sell Stock - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
(Best Time to Buy and Sell Stock 문제는 위 링크에서 풀어보실 수 있습니다.)
< Best Time to Buy and Sell Stock 문제 설명 >
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 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.
주어지는 배열 prices는 prices[i]가 i번째 일의 주식 가격을 의미한다. 주식을 사는 하루를 선택하고, 주식을 팔 미래의 하루를 선택해 수익을 최대화하고자 한다. 거래를 통해 얻을 수 있는 최대의 수익을 리턴하여라. 만약 어떤 수익도 얻을 수 없다면 0을 리턴하여라.
다음 두 가지 출력 예시가 주어졌다.
주어진 제한 조건은 1 ≤ prices.length ≤ 10^5, 0 ≤ prices[i] ≤ 10^4 이다.
< Best Time to Buy and Sell Stock 문제 접근 >
profit을 최대화 하기 위해서 배열 prices에서 최솟값과 최댓값을 찾아 이 둘의 차이를 리턴한다는 방법을 사용하고자 한다. 다만 이 문제에서 주의할 점은, 최솟값을 새로 발견한 경우 최댓값은 이 위치에서부터 다시 찾아야 한다는 것이다. (주식을 산 날보다 먼저 파는 것은 말이 안되므로) 이 조건 하나만 유의하며 알고리즘을 작성해주면 된다. 그 결과는 아래와 같다. (Cpp 사용)
int maxProfit(vector<int>& prices) {
int low = prices[0];
int high = 0;
int profit = 0;
for(int i=1;i<prices.size(); i++){
if(low > prices[i]){ // 최솟값 재설정 시 최댓값 리셋
low = prices[i];
high = 0;
}
high = max(high, prices[i]);
profit = max(profit, high - low);
}
return profit;
}
prices 배열의 index를 1번씩만 훑는 O(n) 복잡도의 코드가 완성되었다.
'2022 Algorithm Study(by leetcode) > Array' 카테고리의 다른 글
[ leetcode 문제풀이 ] Search in Rotated Sorted Array (0) | 2022.02.02 |
---|---|
[ leetcode 문제풀이 ] Find Minimum in Rotated Sorted Array (0) | 2022.02.01 |
[ leetcode 문제풀이 ] Product of Array Except Self (0) | 2022.02.01 |
[ leetcode 문제풀이 ] Contains Duplicate (0) | 2022.02.01 |
[ leetcode 문제풀이 ] Two Sum (0) | 2022.02.01 |