티스토리 뷰

https://www.acmicpc.net/problem/1725

 

1725번: 히스토그램

첫 행에는 N (1 ≤ N ≤ 100,000) 이 주어진다. N은 히스토그램의 가로 칸의 수이다. 다음 N 행에 걸쳐 각 칸의 높이가 왼쪽에서부터 차례대로 주어진다. 각 칸의 높이는 1,000,000,000보다 작거나 같은 자

www.acmicpc.net

 

// https://www.acmicpc.net/problem/1725
// 히스토그램
class Item {
	prev: null | Item = null;
	constructor(public value: any) {}
}

class Stack {
	top: null | Item = null;
	size = 0;
	constructor() {}

	push(value: any) {
		const node = new Item(value);
		node.prev = this.top;
		this.top = node;
		this.size += 1;
	}

	pop() {
		if (this.top) {
			const popItem = this.top;
			this.top = this.top.prev;
			this.size -= 1;
			return popItem.value;
		} else return null;
	}

	peek() {
		return this.top ? this.top.value : null;
	}

	isEmpty() {
		return this.size == 0;
	}
}

const input: string[] = require('fs').readFileSync('./dev/stdin').toString().trim().split('\n');
input.shift();
let answer = 0;
const st = new Stack();
input.forEach((num: any) => {
	num = Number(num);
	if (st.isEmpty()) {
		if (num > answer) answer = num;
		st.push({ h: num, w: 1 });
	} else {
		if (num > answer) answer = num;
		let sz = 0;
		while (!st.isEmpty() && st.peek().h > num) {
			sz = sz == 0 ? st.peek().w : sz + st.peek().w;
			const possible = st.pop().h * sz;
			if (possible > answer) answer = possible;
		}

		if (st.isEmpty() || st.peek().h < num) {
			st.push({ h: num, w: sz + 1 });
		} else if (st.peek().h == num) {
			st.peek().w += sz + 1;
		}
	}
});

let sz = 0;
while (!st.isEmpty()) {
	sz = sz == 0 ? st.peek().w : sz + st.peek().w;
	const max = st.pop().h * sz;
	if (max > answer) answer = max;
}

console.log(answer);
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함