iT邦幫忙

2024 iThome 鐵人賽

DAY 5
0
佛心分享-刷題不只是刷題

轉生理工組後從零開始的leetcode刷題系列 第 5

day-5[easy.1913]maximum product difference between two pairs

  • 分享至 

  • xImage
  •  

The product difference between two pairs (a, b) and (c, d) is defined as (a * b) - (c * d).

For example, the product difference between (5, 6) and (2, 7) is (5 * 6) - (2 * 7) = 16.
Given an integer array nums, choose four distinct indices w, x, y, and z such that the product difference between pairs (nums[w], nums[x]) and (nums[y], nums[z]) is maximized.

Return the maximum such product difference.


翻譯時間:

  • product difference=乘積差(a * b) - (c * d)
    題目大意是要我們在一組數列中找出4個數字,並使他們組成的乘積差最大化。

我的解題思路是這樣:

  1. 做一個陣列,依照大小排列數字。
  2. 取0,1當a,b;最後的兩個數字當c,d。
  3. 很普通的把數字帶入公式,得到乘積差。

印象中有看過可以按照大小排列數字的語法,
後來去查了一下,的確有這種事:Arrays.sort(數組)
所以很簡單地完成了第一步~
Arrays.sort(nums);

然後取出最大的兩個數與最小的兩個數
int max1 = nums[nums.length - 1]; // 最大值
int max2 = nums[nums.length - 2]; // 次大值
int min1 = nums[0]; // 最小值
int min2 = nums[1]; // 次小值

計算乘積差
return (max1 * max2) - (min1 * min2);


丟去leetcode看結果,結束這回合
https://ithelp.ithome.com.tw/upload/images/20240920/20169432WizzmzVWVf.png
老實說我覺得這題是迄今為止最簡單的題目,
等假日時間充裕就可以練練看中等難度的題目了


上一篇
day-4[easy.1812]determine color of a chessboard square
下一篇
day-6[easy.1893]check if all the integers in a range are covered
系列文
轉生理工組後從零開始的leetcode刷題12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言