0
点赞
收藏
分享

微信扫一扫

redis为什么快

彭维盛 2024-09-07 阅读 28

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

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

代码如下:

// 盖楼房
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;
}
}

 

举报

相关推荐

0 条评论