Largest Rectangle

  • + 0 comments

    Java 8 Solution:

    public static long largestRectangle(List<Integer> h) {
                    //1. Iterate the list of height. Set the max height of the building as first element.
                    // then check the height difference to the adjacent building.
                    // If the height is same or more, then go to next building.
                    //Each time find the max rectangle and update the value.
                    long maxRectangle = 0L;
    
                    for(int i = 0; i < h.size(); i++){
                            int maxHt = h.get(i);
                            int maxlen = 1;
                            for(int j = i+1; j < h.size(); j++){
                                    if(h.get(j) - h.get(j-1) < 0){
                                            if(maxHt > h.get(j))maxHt = h.get(j);
                                    }
                                    maxlen+= 1;
                                    if(maxRectangle < maxHt*maxlen) maxRectangle = maxHt*maxlen;
                            }
                    }
                    return maxRectangle;
            }