贪心算法求解拆楼房问题

这是一道典型的贪心算法问题,首先遍历找到一个高度大于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;
    }
}
相关推荐
你撅嘴真丑6 小时前
第九章-数字三角形
算法
uesowys6 小时前
Apache Spark算法开发指导-One-vs-Rest classifier
人工智能·算法·spark
ValhallaCoder6 小时前
hot100-二叉树I
数据结构·python·算法·二叉树
董董灿是个攻城狮6 小时前
AI 视觉连载1:像素
算法
智驱力人工智能7 小时前
小区高空抛物AI实时预警方案 筑牢社区头顶安全的实践 高空抛物检测 高空抛物监控安装教程 高空抛物误报率优化方案 高空抛物监控案例分享
人工智能·深度学习·opencv·算法·安全·yolo·边缘计算
孞㐑¥8 小时前
算法——BFS
开发语言·c++·经验分享·笔记·算法
月挽清风8 小时前
代码随想录第十五天
数据结构·算法·leetcode
XX風8 小时前
8.1 PFH&&FPFH
图像处理·算法
NEXT068 小时前
前端算法:从 O(n²) 到 O(n),列表转树的极致优化
前端·数据结构·算法
代码游侠9 小时前
学习笔记——设备树基础
linux·运维·开发语言·单片机·算法