참고
문제해설
문제 로직고민
NOTE
•
가장 최적의 구매는 가장 낮은 가격에서 만들어진다.
◦
배열을 순회하면서 가장 낮은 값을 기준으로 각 idx별로 얼마나 순이익을 얻을 수 있는가 계산한다.
◦
가장 낮은 값은 순회하면서 계속해서 비교하며 갱신한다.
작성코드
NOTE
class Solution {
public int maxProfit(int[] prices) {
int idx = 0;
int max = 0;
for(int i = 1; i < prices.length; i++){
if(prices[idx] < prices[i]) {
max = Math.max(max, prices[i] - prices[idx]);
}
else{
idx = i;
}
}
return max;
}
}
Java
복사
정답코드
NOTE
class Solution {
public int maxProfit(int[] prices) {
int profit=0;
int price=Integer.MAX_VALUE;
for(int i=0;i<prices.length;i++)
{
if(price>prices[i])
{
price=prices[i];
}
else if(prices[i]-price>profit)
profit=prices[i]-price;
}
System.gc();
return profit;
}
}
Java
복사
메모리를 가장 적게 사용하는 코드
•
메모리 사용량 부분에서 상당히 좋지 않은 결과를 얻었는데, Math 라이브러리를 사용한것이 문제인것 같다.
•
이외에는 로직상 정답코드하고 크게 차이가 없어보인다.