贪心算法求解拆楼房问题

这是一道典型的贪心算法问题,首先遍历找到一个高度大于0的楼房,然后以此为基准,划分一个区间,找到楼房内高度最小的楼房,每次都减去这个高度最小的值。

后续重复一样,再找减去后楼房高度的最小值,每次减去这个值,直到所有楼房为0.

代码如下:

java 复制代码
// 盖楼房
import java.util.Scanner;

public class Solution22 {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the number of buildings (n): ");
        int n = scanner.nextInt();

        int[] heights = new int[n];
        System.out.println("Enter the heights of the buildings:");
        for (int i = 0; i < n; i++) {
            heights[i] = scanner.nextInt();
        }

        int operations = minimizeOperations(heights);
        System.out.println("Minimum operations needed: " + operations);
    }

    public static int minimizeOperations(int[] heights) {
        int operations = 0;
        int n = heights.length;

        while (true) {
            int start = -1;
            for (int i = 0; i < n; i++) {
                if (heights[i] > 0) {
                    start = i;
                    break;
                }
            }

            if (start == -1) {
                break; // All buildings are zero height
            }

            int minHeight = heights[start];
            int end = start;
            for (int i = start; i < n && heights[i] > 0; i++) {
                minHeight = Math.min(minHeight, heights[i]);
                end = i;
            }

            for (int i = start; i <= end; i++) {
                heights[i] -= minHeight;
            }

            operations++;
            System.out.println("Operation " + operations + ": Reduce buildings from " + start + " to " + end + " by " + minHeight);
        }

        return operations;
    }
}
相关推荐
rit84324996 小时前
基于GA-GM(1,1)模型的航空发电机状态趋势分析实现
算法
CQ_YM6 小时前
数据结构之哈希表
数据结构·算法·哈希算法·哈希表
pursuit_csdn6 小时前
力扣周赛 - 479
算法·leetcode·职场和发展
飞天狗1116 小时前
C. Needle in a Haystack
算法
FMRbpm6 小时前
顺序表实现队列
数据结构·c++·算法·新手入门
飞天狗1116 小时前
G. Mukhammadali and the Smooth Array
数据结构·c++·算法
CQ_YM6 小时前
数据结构之树
数据结构·算法·
某林2126 小时前
SLAM 建图系统配置与启动架构
人工智能·stm32·单片机·嵌入式硬件·算法
不穿格子的程序员6 小时前
从零开始写算法——矩阵类题:图像旋转 + 搜索二维矩阵 II
线性代数·算法·矩阵
罗湖老棍子7 小时前
Knight Moves(信息学奥赛一本通- P1257)
c++·算法·bfs