푸는 방법은 총 세가지이다. (참고)
stack으로도 풀어봐야겠다.
function largestRectangle(h) {
// Write your code here
const array = h.slice();
let max = Number.MIN_SAFE_INTEGER;
for (let i = 0; i < array.length; i++) {
const point = array[i];
// 앞 빌딩이 나보다 같거나 큰 경우 앞에도 확인
// 단, 인덱스가 0인 경우는 뒤에만 확인
// 뒷 빌딩이 나보다 같거나 큰 경우 뒤에도 확인
// 단, 마지막 인덱스인 경우는 앞에만 확인
let count = 1; // 나는 무조건 포함
// 앞에도 확인
if (i > 0 && array[i - 1] >= point) {
let j = i - 1;
while (j >= 0 && array[j] >= point) {
count++;
j -= 1;
}
}
// 뒤에도 확인
if (i < array.length - 1 && array[i + 1] >= point) {
let j = i + 1;
while (j < array.length && array[j] >= point) {
count++;
j += 1;
}
}
if (max < point * count) {
max = point * count;
}
}
return max;
}
console.log(largestRectangle([3, 2, 3])); // 6
console.log(largestRectangle([1, 2, 3, 4, 5])); // 9
console.log(largestRectangle([1])); // 1
console.log(largestRectangle([100, 1, 99, 98, 3, 4]));
console.log(
largestRectangle([6320, 6020, 6098, 1332, 7263, 672, 9472, 2838, 3401, 9494])
); // 18060
'Programming > 데일리 알고리즘' 카테고리의 다른 글
[HackerRank] Minimum Swaps 2 (javascript) (0) | 2021.05.30 |
---|---|
[HackerRank] Special String Again (javascript) (0) | 2021.05.29 |
(210519:BTB) Lesson 6. MaxProductOfThree (0) | 2021.05.19 |
(210519:BTB) Lesson 6. Distinct (0) | 2021.05.19 |
[HackerRank] Balanced Brackets (Javascript) (0) | 2021.05.18 |