4.19打卡

问题描述:

给定一个长度为n的数组,找出其中的最大元素和最小元素的差值。假设数组中的元素范围为[-10000, 10000]。

设计思路:
1. 直接排序,取出最大值和最小值,计算其差值;
2. 遍历数组,同时维护最大值和最小值,最后计算其差值。

 

程序流程图:
1. 直接排序,取出最大值和最小值,计算其差值

2. 遍历数组,同时维护最大值和最小值,最后计算其差值

 

代码实现:
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>

using namespace std;

int maxMinDiff(vector<int>& nums) {

int minNum = INT_MAX, maxNum = INT_MIN;
for (int num : nums) {
minNum = min(minNum, num);
maxNum = max(maxNum, num);
}
return maxNum - minNum;
}

int main() {
vector<int> nums = {1, 5, -3, 4, 10};
cout << maxMinDiff(nums) << endl;

nums = {0, 0, 0, 0};
cout << maxMinDiff(nums) << endl;

nums = {INT_MAX, INT_MIN};
cout << maxMinDiff(nums) << endl; 

return 0;
}

posted @   晨观夕  阅读(11)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
点击右上角即可分享
微信分享提示