문제
prices는 배열이며, 각 요소는 매일의 주식 가격입니다. 만약 한 번만 거래할 수 있다면 = 사고 팔 수 있다면, 제일 큰 이익은 얼마일까요?
Input: [7,1,5,3,6,4]
Output: 5
설명: 2일(가격=1)에 샀다가 5일(가격=6)에 사는 것이 6-1이라 제일 큰 수익 7-1=6 은 안 되는거 아시죠? 먼저 사야 팔 수 있습니다.
Input: [7,6,4,3,1]
Output: 0
설명: 여기서는 매일 가격이 낮아지기 때문에 거래가 없습니다. 그래서 0
풀이 1
const maxProfit = prices => {
let reverse = prices.reverse() // 인자 배열 reverese
let returnValue = 0; // 최종 리턴 최댓값 ( 없을 경우 0 )
for (let i=0; i<reverse.length; i++)
{
for (let j=i+1; j<reverse.length; j++)
{
returnValue = Math.max(returnValue,reverse[i]-reverse[j])
}
console.log(returnValue)
}
return returnValue;
};
maxProfit([7,1,5,3,6,4]);
풀이2
const maxProfit = prices => {
//산값(작은수)
let buy = 0;
//판값(큰수)
let sell = 0;
//최대 비교값
let max = 0;
for(let i = 0; i < prices.length; i++){
//최대이윤은 판날에서 산날을 뺀다
const profit = prices[sell] - prices[buy]
//프로핏이 0보다 작으면 산값은 판값이 되는거고
if(profit < 0){
buy = sell;
}
//최대값이(차익) 이윤보다 작으면 최대값이 이윤이랑 같아진다
if(max < profit){
max = profit;
}
//for문을 돌리면서 파는 값을 키우면서 비교
sell++;
}
return max;
};
console.log(maxProfit([7,1,5,3,6,4]))
풀이3
const maxProfit = (prices) => {
let num = 0;
let numMax = Math.max(...prices); // 배열에서 최고값
let numMin = Math.min(...prices); // 배열에서 최소값
let maxIndex = prices.indexOf(numMax); // 최고값의 index
if (maxIndex === 0) {
// 최고값의 index = 0 이면, 배열 첫번째 값 삭제 후 다시 최고값과 index 찾음
prices.shift();
numMax = Math.max(...prices);
maxIndex = prices.indexOf(numMax);
}
let minIndex = prices.indexOf(numMin); // 최소값의 index
if (maxIndex > minIndex) {
// index 값 비교(최고값의 index가 최소값의 index보다 뒤에 있으면 뺄셈)
num = numMax - numMin;
return num;
} else {
return num;
}
};