贪心算法求解拆楼房问题

这是一道典型的贪心算法问题,首先遍历找到一个高度大于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;
    }
}
相关推荐
点云侠16 分钟前
【2025最新版】PCL点云处理算法汇总(C++长期更新版)
c++·算法·计算机视觉·3d·可视化
zaiyang遇见1 小时前
【递归完全搜索】CCC 2008 - 24点游戏Twenty-four
算法·游戏·c/c++·全排列·信息学奥赛
Python智慧行囊1 小时前
排序算法总结
数据结构·算法
似水流年流不尽思念1 小时前
常见的排序算法有哪些?它们的平均时间复杂度是多少?
后端·算法
楽码2 小时前
端到端应用Hmac加密
服务器·后端·算法
Morriser莫2 小时前
图论Day2学习心得
算法·图论
zyd09152 小时前
代码随想录Day50:图论(图论理论、深度搜索理论、所有可达路径、广度搜索理论)
java·数据结构·算法·leetcode·图论
Cl_rown去掉l变成C2 小时前
第R5周:天气预测
人工智能·python·深度学习·算法·tensorflow2
CoovallyAIHub3 小时前
VisDrone数据集,专为无人机视觉任务打造
深度学习·算法·计算机视觉
啊阿狸不会拉杆3 小时前
《算法导论》第 22 章 - 基本的图算法
c++·算法·排序算法·图论·拓扑学