贪心算法求解拆楼房问题

这是一道典型的贪心算法问题,首先遍历找到一个高度大于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;
    }
}
相关推荐
zxsz_com_cn1 天前
设备预测性维护算法核心功能有哪些?六大模块拆解智能运维的“技术骨架”
运维·算法
期末考复习中,蓝桥杯都没时间学了1 天前
力扣刷题13
数据结构·算法·leetcode
2201_756989091 天前
C++中的事件驱动编程
开发语言·c++·算法
多米Domi0111 天前
0x3f 第48天 面向实习的八股背诵第五天 + 堆一题 背了JUC的题,java.util.Concurrency
开发语言·数据结构·python·算法·leetcode·面试
2301_822377651 天前
模板元编程调试方法
开发语言·c++·算法
故以往之不谏1 天前
函数--值传递
开发语言·数据结构·c++·算法·学习方法
渐暖°1 天前
【leetcode算法从入门到精通】5. 最长回文子串
vscode·算法·leetcode
今天_也很困1 天前
LeetCode热题100-560. 和为 K 的子数组
java·算法·leetcode
v_for_van1 天前
力扣刷题记录2(无算法背景,纯C语言)
c语言·算法·leetcode
2301_811232981 天前
低延迟系统C++优化
开发语言·c++·算法