最小化任一端的删除以从数组中删除最小值和最大值
给定大小为N的整数数组arr[] ,任务是找到最小删除操作的计数,以从数组中删除最小和最大元素。只能从数组的任一端删除元素。
例子:
Input: arr = [2, 10, 7, 5, 4, 1, 8, 6]
Output: 5
Explanation: The minimum element is 1 and the maximum element is 10. We can visualise the deletion operations as below:
[2, 10, 7, 5, 4, 1, 8, 6]
[2, 10, 7, 5, 4, 1, 8]
[2, 10, 7, 5, 4, 1]
[2, 10, 7, 5, 4]
[10, 7, 5, 4]
[7, 5, 4]
Total 5 deletion operations performed. There is no other sequence with less deleitions in which the minimum and maximum can be deleted.
Input: arr = [56]
Output: 1
Explanation: Because the array only has one entry, it serves as both the lowest and maximum value. With a single delete, we can eliminate it.
Input: arr = [2, 5, 8, 3, 6, 4]
Output: 3
Explanation: The minimum element is 2 and the maximum element is 8. We can visualise the deletion operations as below:
[2, 5, 8, 3, 6, 4]
[5, 8, 3, 6, 4]
[8, 3, 6, 4]
[3, 6, 4]
Total 3 deletions are performed. It is the minimum possible number of deletions.
方法:上述问题可以通过以下观察来解决:
假设 max 和 min 元素存在于索引 i 和 j 处,反之亦然,如下所示:
在哪里,
- i, j : 数组的最大或最小元素的索引
- a : 最小(或最大)元素到起点的距离
- b :最小和最大元素之间的距离
- c :最大(或最小)元素与结束之间的距离
- N : 数组的长度
现在让我们看看不同的可能删除方式:
- 从 start中删除一个,从 end中删除另一个:
No. of deletion = (a + c) = ( (i + 1) + (n – j) )
- 要从数组的开头删除它们:
No. of deletion = (a + b) = (j + 1)
- 要从数组末尾删除它们:
No. of deletion = (b + c) = (n – i)
使用上述等式,我们现在可以使用 min 和 max 元素的索引轻松获得距离。答案是这3种情况中的最小值
下面是上述方法的实现:
C++
Java
Python3
C#
Javascript
时间复杂度: O(N)
辅助空间: O(1)