Search
Duplicate
📒

[LeetCode Top 150] 01-8. Best Time to Buy and Sell Stock 2 - Medium

상태
완료
수업
Algorithm Solving
주제
LeetCode Top Interview 150
4 more properties
참고

문제해설

NOTE
입력 값 ⇒ 주식 가격이 있는 정수배열
출력 값 ⇒ 매일 주식을 매수/매도 할 수 있는 상황에서, 최대 이익

문제 로직고민

NOTE
주식의 미래시를 볼 수 있는 무적의 트레이더는 나도 해보고 싶다.
오늘 주식이 내일 오른다 → 사서 판매
이거 하나만 할 수 있다면 나도 부자가 될 수 있다…

작성코드

NOTE
class Solution { public int maxProfit(int[] prices) { int result = 0; for(int i = 0; i < prices.length -1; i++){ if(prices[i] < prices[i+1]){ result += prices[i+1] - prices[i]; } } return result; } }
Java
복사
구매/판매 횟수의 제한이 없어 가장 단순하게 풀 수 있었다.
1,2,3,4,5,6 의 주식인 경우
1을 6에서 파나, 하루마다 사고팔고 해도 이익은 같기떄문

정답코드

NOTE
class Solution { public int maxProfit(int[] prices) { int sum = 0; for (int i = 0; i < prices.length - 1; ++i) { int div = prices[i+1] - prices[i]; //System.out.println(div); if(div > 0) sum += div; } System.gc(); return sum; } }
Java
복사
메모리를 가장 적게 사용하는 코드
로직은 같은데 system.gc()가 있다는 차이점만 있다.
메모리도 사실상 3MB정도의 차이이니 크게 건드릴게 없는듯하다.