[Programming question] Maximum rectangular area (Meituan Review 2017 Autumn Recruitment)

Time limit: 1 second
Space limit: 32768K

Given an array h of non-negative integers, representing the heights of a set of bars, where each bar has a width of 1. Find the area of ​​the largest rectangle that can be formed in this set of histograms (as shown). The input parameter h is an integer array, representing the height of each column, and returns the value of the area.

Histogram

Input description: The input consists of two lines, the first line contains an integer n (1≤n≤10000), the second line includes n integers, representing each value in the h array, h_i (1 ≤ h_i ≤ 1,000,000)

Output description: Output an integer representing the largest matrix area.

Input example:
6
2 1 5 6 2 3

Example output:
10

Idea: Select each column in turn, and find the largest rectangle extended by each column, then the largest rectangle is what we want.

Code:

import java.util.*;
public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[]arr = new int[n];
        for(int i = 0; i < arr.length; i++) {
            arr[i] = sc.nextInt();
        }
        System.out.println(ans(arr));
    }
    public static int ans(int[] arr) {
        int max = 0;
        for(int i = 0; i < arr.length; i++) {
            int temp = arr[i];
            //向左扩展
            for(int left = i - 1; left >=0; left--) {
                if(arr[left] < arr[i]) {
                    break;
                }else {
                    temp += arr[i];
                }
            }
            //向右扩展
            for(int right = i + 1; right < arr.length; right++) {
                if(arr[right] < arr[i]) {
                    break;
                }else {
                    temp += arr[i];
                }
            }
            if(temp > max) {
                max = temp;
            }
        }
        return max;
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325817871&siteId=291194637