๐ 1. ๋ฌธ์
121. Best Time to Buy and Sell Stock
์ฌ๊ณ ํ์์ ๋ ๊ฐ์ฅ ํฐ ์ด์ต ์ฐพ๊ธฐ
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.
โ ํ์ด
1์ฐจ ์๋
var maxProfit = function (prices) {
let max = 0;
for (let i = 0; i < prices.length; i++) {
for (let j = i + 1; j < prices.length; j++) {
if (prices[j] - prices[i] > max) {
max = prices[j] - prices[i];
}
}
}
return max;
};
- ๋จ์ํ ์ด์ค for๋ฌธ์ ๋๋ ค์ max๊ฐ์ ์ฐพ์ผ๋ฉด ๋ ์ค ์์๋ค. ๊ฒฐ๊ณผ๋ ๋ง์ง๋ง ์๊ฐ์ด๊ณผ๋ก ๋ค๋ฅธ ๋ฐฉ์์ ์๊ฐํด์ผํ๋ค.
2์ฐจ ์๋
var maxProfit = function (prices) {
let min = prices[0];
let max = 0;
for (let i = 1; i < prices.length; i++) {
if (prices[i] < min) min = prices[i];
else if (prices[i] - min > max) {
max = prices[i] - min;
}
}
return max;
};
- for๋ฌธ์ ๋๋ฒ ๋๋ฆฌ์ง ์๊ณ for๋ฌธ์ด ํ๋ฒ ๋๋๋ง๋ค ์ต์๊ฐ๊ณผ ์ต๋๊ฐ, ๊ฒฐ๊ณผ ๊ฐ์ ๋ชจ๋ ๊ฐฑ์ ์์ผ์ฃผ๋ ๋ฐฉ๋ฒ์ ์ฌ์ฉํ๋ค.
๐ 2. ๋ฌธ์
20. Valid Parentheses
์ฌ๋ฐ๋ฅธ ๊ดํธ์ธ์ง ํ๋ณํ๊ธฐ
Input: s = โ(]โ
Output: false
Input: s = โ{[]}โ
Output: true
โ ํ์ด
1์ฐจ ์๋
var isValid = function (s) {
let answer = true;
let stack = [];
for (let i = 0; i < s.length; i++) {
if (s[i] === "(" || s[i] === "[" || s[i] === "{") {
stack.push(s[i]);
} else {
if (stack.length === 0) answer = false;
if (s[i] === ")" && stack[stack.length - 1] === "(") {
stack.pop();
} else if (s[i] === "]" && stack[stack.length - 1] === "[") {
stack.pop();
} else if (s[i] === "}" && stack[stack.length - 1] === "{") {
stack.pop();
} else {
answer = false;
}
}
}
if (stack.length !== 0) answer = false;
return answer;
};
- stack ์๋ฃ๊ตฌ์กฐ๋ฅผ ์ฌ์ฉํ๋ค. ์ฌ๋ ๊ดํธ์ผ ๋๋ ์คํ์ pushํ๊ณ ๋ซ๋ ๊ดํธ ์ผ๋๋ ์คํ์ ๋ง์ง๋ง ์์๊ฐ ๋ซ๋ ๊ดํธ์ ์ง์ธ์ง ํ์ธํ ํ, ๋ง๋ค๋ฉด ๋ง์ง๋ง ์์๋ pop์ํค๋ ์ฝ๋๋ฅผ ์์ฑํ๋ค.