华为OD【水库蓄水问题】


LeetCode42变体
在原题的基础上找出最大的一个坑的蓄水量

import java.util.Scanner;
public class Demo {
    public static void main(String[] args) {
        /*
1 8 6 2 5 4 8 3 7

100 1 100 200 100 150


         */
        Scanner scanner = new Scanner(System.in);
        String s = scanner.nextLine();
        if(s.isEmpty()){
            System.out.print(-1);
            return;
        }
        String[] temp_params = s.split(" ");
        int[] params = new int[temp_params.length];
        for(int i = 0; i < temp_params.length; i++){
            params[i] = Integer.parseInt(temp_params[i]);
        }
        int head = 0, tail = 0;
        int[] res = new int[]{head,tail,0};
        //计算水库的蓄水量
        int[] capacity = caculate_capacity(params);
        int current_capacity = 0;
        while(tail < capacity.length){
            current_capacity = 0;
            while(tail < capacity.length && capacity[tail] == 0){
                tail++;
                head = tail;
            }
            if(head == capacity.length){
                break;
            }
            while(tail < capacity.length && capacity[tail] != 0){
                current_capacity += capacity[tail++];
            }
            if(res[2] <= current_capacity){
                res[0] = --head;
                res[1] = tail;
                res[2] = current_capacity;
            }
        }
        System.out.print(res[0] + " " + res[1] + ":" + res[2]);
    }
    public static int[] caculate_capacity(int[] params){
        int size = params.length;
        int[] left_boundary = new int[size];
        int[] right_boundary = new int[size];
        int max_hight = params[0];
        //计算每个点左侧的最大值
        for(int i = 0; i <= size - 1; i++){
            max_hight = max_hight > params[i] ? max_hight : params[i];
            left_boundary[i] = max_hight;
        }
        max_hight = params[size - 1];
        //计算每个电右侧的最大值
        for(int i = size - 1; i >= 0; i--){
            max_hight = max_hight > params[i] ? max_hight : params[i];
            right_boundary[i] = max_hight;
        }
        for(int i = 0; i <= size - 1; i++){
            left_boundary[i] = Math.min(left_boundary[i],right_boundary[i]) - params[i];
        }
        return left_boundary;
    }
}
posted @ 2025-04-23 11:13  破忒头头  阅读(21)  评论(0)    收藏  举报