본문 바로가기

라이브러리/JAVA

히스토그램 최대 넓이

전처리

static class Pair
{
    int index;
    int height;

    Pair(int index, int height) { this.index = index; this.height = height; }
}

 

 

히스토그램 최대 넓이

static int Histogram_Max_Space (int[] hist, int N)
{
    int ans = 0;
    Stack<Pair> stack = new Stack<>();

    for (int i=0; i<N; i++)
    {
        int height = hist[i];

        Pair current = new Pair(i, height);

        int changed_index = i;

        if ( stack.isEmpty() )
        {
            stack.push(current);
            continue;
        }

        while ( !stack.isEmpty() && stack.peek().height > current.height )
        {
            Pair poped = stack.pop();
            int space = poped.height * ( current.index - poped.index );
            ans = Math.max(ans, space);
            changed_index = poped.index;
        }

        current.index = changed_index;

        stack.push(current);
    }

    while ( !stack.isEmpty() )
    {
        Pair poped = stack.pop();
        int space = poped.height * ( N - poped.index );
        ans = Math.max(ans, space);
    }

    return ans;
}

 

'라이브러리 > JAVA' 카테고리의 다른 글

변형 인접리스트  (0) 2024.08.08
벨만 포드  (2) 2024.07.28
에라체  (0) 2024.07.08
분할정복 거듭제곱  (1) 2024.07.08
플로이드 워셜  (1) 2024.07.03