给定表示建筑物高度的整数数组H和整数K。任务是使用以下规则从第一座建筑到达最后一座建筑:
- 只有在| H i – H j |的情况下,才能从高度为H i的建筑物到达高度为H j的建筑物。 <= K ,建筑物在阵列中一个接一个地出现。
- 如果无法到达建筑物,则可以在两座建筑物之间插入许多中间高度的建筑物。
找到在第2步中完成的最少插入次数,以使从第一个建筑到最后一个建筑成为可能。
例子:
Input: H[] = {2, 4, 8, 16}, K = 3
Output: 3
Add 1 building of height 5 between buildings of height 4 and 8.
And add 2 buildings of heights 11 and 14 respectively between buildings of height 8 and 16.
Input: H[] = {5, 55, 100, 1000}, K = 10
Output: 97
方法:
- 运行从1到n-1的循环,并检查
abs(H[i] - H[i-1]) <= K
- 如果上述条件为真,则跳到循环的下一个迭代。
- 如果条件为假,则所需的插入将等于
ceil(diff / K) - 1
其中diff = abs(H[i] - H[i-1])
- 最后打印总插入数。
下面是上述方法的实现:
C++
// CPP implementation of above approach
#include
using namespace std;
// Function to return minimum
// number of insertions required
int minInsertions(int H[], int n, int K)
{
// Initialize insertions to 0
int inser = 0;
for (int i = 1; i < n; ++i) {
float diff = abs(H[i] - H[i - 1]);
if (diff <= K)
continue;
else
inser += ceil(diff / K) - 1;
}
// return total insertions
return inser;
}
// Driver program
int main()
{
int H[] = { 2, 4, 8, 16 }, K = 3;
int n = sizeof(H) / sizeof(H[0]);
cout << minInsertions(H, n, K);
return 0;
}
Java
// Java implementation of above approach
class GFG{
// Function to return minimum
// number of insertions required
static int minInsertions(int[] H, int n, int K)
{
// Initialize insertions to 0
int inser = 0;
for (int i = 1; i < n; ++i) {
float diff = Math.abs(H[i] - H[i - 1]);
if (diff <= K)
continue;
else
inser += Math.ceil(diff / K) - 1;
}
// return total insertions
return inser;
}
// Driver program
public static void main(String[] args)
{
int[] H = new int[]{ 2, 4, 8, 16 };
int K = 3;
int n = H.length;
System.out.println(minInsertions(H, n, K));
}
}
// This code is contributed by mits
Python3
# Python3 implementation of above approach
import math
# Function to return minimum
# number of insertions required
def minInsertions(H, n, K):
# Initialize insertions to 0
inser = 0;
for i in range(1, n):
diff = abs(H[i] - H[i - 1]);
if (diff <= K):
continue;
else:
inser += math.ceil(diff / K) - 1;
# return total insertions
return inser;
# Driver Code
H = [2, 4, 8, 16 ];
K = 3;
n = len(H);
print(minInsertions(H, n, K));
# This code is contributed
# by mits
C#
// C# implementation of above approach
using System;
class GFG
{
// Function to return minimum
// number of insertions required
static int minInsertions(int[] H,
int n, int K)
{
// Initialize insertions to 0
int inser = 0;
for (int i = 1; i < n; ++i)
{
float diff = Math.Abs(H[i] - H[i - 1]);
if (diff <= K)
continue;
else
inser += (int)Math.Ceiling(diff / K) - 1;
}
// return total insertions
return inser;
}
// Driver Code
static void Main()
{
int[] H = new int[]{ 2, 4, 8, 16 };
int K = 3;
int n = H.Length;
Console.WriteLine(minInsertions(H, n, K));
}
}
// This code is contributed by mits
PHP
输出:
3