hackerrank :Equal Stacks 等高栈

You have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times.

Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of the three stacks until they're all the same height, then print the height. The removals must be performed in such a way as to maximize the height.

原题描述点击这里


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n1 = in.nextInt();
        int n2 = in.nextInt();
        int n3 = in.nextInt();
        int h1[] = new int[n1];
        for (int h1_i = 0; h1_i < n1; h1_i++) {
            h1[h1_i] = in.nextInt();
        }
        int h2[] = new int[n2];
        for (int h2_i = 0; h2_i < n2; h2_i++) {
            h2[h2_i] = in.nextInt();
        }
        int h3[] = new int[n3];
        for (int h3_i = 0; h3_i < n3; h3_i++) {
            h3[h3_i] = in.nextInt();
        }
        in.close();
        Stack<NodeWithMax> s1 = arrayToStack(h1);
        Stack<NodeWithMax> s2 = arrayToStack(h2);
        Stack<NodeWithMax> s3 = arrayToStack(h3);
        while (!s1.isEmpty() && !s2.isEmpty() && !s3.isEmpty()) {
            if ((s3.peek().max == s2.peek().max) && (s3.peek().max == s1.peek().max)) {
                System.out.println(s3.pop().max);
                return;
            }
            if (s1.peek().max > s2.peek().max || s1.peek().max > s3.peek().max) {
                s1.pop();
                continue;
            }
            if (s2.peek().max > s1.peek().max || s2.peek().max > s3.peek().max) {
                s2.pop();
                continue;
            }
            if (s3.peek().max > s2.peek().max || s3.peek().max > s1.peek().max) {
                s3.pop();
                continue;
            }

        }
        System.out.println(0);

    }

    private static Stack<NodeWithMax> arrayToStack(int[] h1) {
        Stack<NodeWithMax> tmps = new Stack<NodeWithMax>();
        for (int i = h1.length - 1; i >= 0; i--) {
            NodeWithMax tmpnode = new NodeWithMax();
            tmpnode.data = h1[i];
            tmpnode.max = tmpnode.data + (tmps.isEmpty() ? 0 : tmps.peek().max);
            tmps.add(tmpnode);
        }
        return tmps;
    }
}

class NodeWithMax {
    int data;
    int max;

}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容