当前位置:网站首页>1913. 两个数对之间的最大乘积差-无需排序法
1913. 两个数对之间的最大乘积差-无需排序法
2022-07-25 23:21:00 【Mr Gao】
1913. 两个数对之间的最大乘积差-无需排序法
两个数对 (a, b) 和 (c, d) 之间的 乘积差 定义为 (a * b) - (c * d) 。
例如,(5, 6) 和 (2, 7) 之间的乘积差是 (5 * 6) - (2 * 7) = 16 。
给你一个整数数组 nums ,选出四个 不同的 下标 w、x、y 和 z ,使数对 (nums[w], nums[x]) 和 (nums[y], nums[z]) 之间的 乘积差 取到 最大值 。
返回以这种方式取得的乘积差中的 最大值 。
示例 1:
输入:nums = [5,6,2,7,4]
输出:34
解释:可以选出下标为 1 和 3 的元素构成第一个数对 (6, 7) 以及下标 2 和 4 构成第二个数对 (2, 4)
乘积差是 (6 * 7) - (2 * 4) = 34
示例 2:
输入:nums = [4,2,5,9,7,4,8]
输出:64
解释:可以选出下标为 3 和 6 的元素构成第一个数对 (9, 8) 以及下标 1 和 5 构成第二个数对 (2, 4)
乘积差是 (9 * 8) - (2 * 4) = 64
看到这个题目,很多人第一反应可能是排序,但其实,如果用排序那就慢了,我们可以不需要排序,也可以可以找到最大的两个数和最小的两个数,解题代码如下:
int maxProductDifference(int* nums, int numsSize){
int min1=0,max1=0;
int min2=1,max2=1;
for(int i=2;i<numsSize;i++){
if(nums[i]>nums[max1]&&nums[i]>nums[max2]){
if(nums[max1]>nums[max2]){
max2=i;
}
else{
max1=i;
}
}
else if(nums[i]>nums[max1]&&nums[i]<=nums[max2]){
max1=i;
}
else if(nums[i]<=nums[max1]&&nums[i]>nums[max2]){
max2=i;
}
if(nums[i]<nums[min1]&&nums[i]<nums[min2]){
if(nums[min1]>nums[min2]){
min1=i;
}
else{
min2=i;
}
}
else if(nums[i]<nums[min1]&&nums[i]>=nums[min2]){
min1=i;
}
else if(nums[i]>=nums[min1]&&nums[i]<nums[min2]){
min2=i;
}
}
printf ("mx %d %d %d %d",min1,min2,max1,max2);
return nums[max1]*nums[max2]-nums[min1]*nums[min2];
}
边栏推荐
- The difference between MySQL clustered index and non clustered index
- ETL工具(数据同步) 二
- Zero crossing position search of discrete data (array)
- [QNX hypervisor 2.2 user manual]9.6 GDB
- Ffmpeg first learning (only for coding)
- uvm_ HDL -- implementation of DPI in UVM (4)
- Wamp MySQL empty password
- Unity uses macros
- npm+模块加载机制
- Strategy mode_
猜你喜欢
随机推荐
@Import
Ffmpeg first learning (only for coding)
Secure code warrior learning record (III)
Scaffold installation
@Autowired注解 required属性
What has Amazon cloud technology done right to become the leader of cloud AI services for three consecutive years?
自定义mvc原理
网格参数化Least Squares Conformal Maps实现(3D网格映射到2D平面)
E-commerce RPA, a magic weapon to promote easy entry
CTS测试方法「建议收藏」
[QNX Hypervisor 2.2用户手册]9.8 load
POI特效 市场调研
Data broker understanding
JS regular expression matches IP address (IP address regular expression verification)
Network Security Learning notes-1 file upload
Tips for using (1)
新手哪个券商开户最好 开户最安全
ASP date function (what if the disk function is incorrect)
Wamp MySQL empty password
2021-09-30









