使用C++编写代码,找到具有相同最小值和最大值的子数组的数量

2023年 8月 27日 52.6k 0

使用C++编写代码,找到具有相同最小值和最大值的子数组的数量

在本文中,我们将使用C++解决寻找最大值和最小值相同的子数组数量的问题。以下是该问题的示例−

Input : array = { 2, 3, 6, 6, 2, 4, 4, 4 }
Output : 12
Explanation : {2}, {3}, {6}, {6}, {2}, {4}, {4}, {4}, {6,6}, {4,4}, {4,4} and { 4,4,4 } are the subarrays which can be formed with maximum and minimum element same.

Input : array = { 3,3,1,5,1,2,2 }
Output : 9
Explanation : {3}, {3}, {1}, {5}, {1}, {2}, {2}, {3,3} and {2,2} are the subarrays which can be formed with minimum and maximum are the same.

登录后复制

求解的方法

通过示例,我们可以说,使用等于数组大小的相同最小和最大元素可以形成最小数量的子数组。如果连续的数字相同,子数组的数量可以更多。

所以我们可以采用遍历每个元素,检查其连续的数字是否相同的方法,如果连续的数字则增加计数相同,如果发现不同的数字则中断内循环。

每次内循环结束或中断时,结果变量都会增加结果变量,最后显示结果变量的结果。

p>

示例

#include
using namespace std;
int main(){
int a[ ] = { 2, 4, 5, 3, 3, 3 };
int n = sizeof(a) / sizeof(a[0]);
int result = n, count =0;
for (int i = 0; i < n; i++) {
for (int j = i+1; j < n; j++) {
if(a[i]==a[j])
count++;
else
break;
}
result+=count;
count =0;
}
cout

相关文章

JavaScript2024新功能:Object.groupBy、正则表达式v标志
PHP trim 函数对多字节字符的使用和限制
新函数 json_validate() 、randomizer 类扩展…20 个PHP 8.3 新特性全面解析
使用HTMX为WordPress增效:如何在不使用复杂框架的情况下增强平台功能
为React 19做准备:WordPress 6.6用户指南
如何删除WordPress中的所有评论

发布评论