[LeetCode]주식을 사고팔기 가장 좋은 시점

Inhwan98·2023년 1월 30일
0

PTU STUDY_leetcode

목록 보기
11/24

문제

한 번의 거래로 낼 수 있는 최대 이익을 산출하라.

예제

  • Example 1:
Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
  • Example 2:
Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

코드

class Solution {
public:
    int maxProfit(vector<int>& prices) {
    
	int sum = 0;
	int smallnum = prices[0];

	for (auto iter = prices.begin()+1; iter != prices.end(); ++iter)
	{
		smallnum = min(smallnum, *iter);
		sum = max(sum, *iter - smallnum);
	}
    return sum;
    
    }
};

풀이

1.

int smallnum = prices[0];
  • smallnum변수에 prices의 첫 번째 인덱스 값을 넣어 준다.

2.

for (auto iter = prices.begin()+1; iter != prices.end(); ++iter)
	{
		smallnum = min(smallnum, *iter);
		sum = max(sum, *iter - smallnum);
	}
  • smallnum의 값과 현재 반복자의 값을 비교하여 smallnum에 더 작은 값을 넣어주고,
    현재 반복자의 값에서 smallnum을 뺀 값중 최대 값을 찾기위해 계속 비교해서 sum에 넣어준다.

결과

Runtime 138 ms / Memory 93.5 MB
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/submissions/887967256/


https://leetcode.com/problems/best-time-to-buy-and-sell-stock/

profile
코딩마스터

0개의 댓글