iT邦幫忙

2024 iThome 鐵人賽

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

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

day-10[easy.2016]maximum difference between increasing elements

  • 分享至 

  • xImage
  •  

Given a 0-indexed integer array nums of size n, find the maximum difference between nums[i] and nums[j] (i.e., nums[j] - nums[i]), such that 0 <= i < j < n and nums[i] < nums[j].

Return the maximum difference. If no such i and j exists, return -1.


題目大意是在數組中找到兩個數字i,j,j-i有最大差值,且i小於j,i位於j左側。
如果如果數組往右漸減(不存在正差值),就輸出-1。
我的解題思路:

  1. 遍歷數組,對每一個數字都計算一次與其右邊所有數字的差值
  2. 除去差值為負的項目
  3. 比較出最大的差值並輸出

class Solution {
public int maximumDifference(int[] nums) {
// 初始化最大差值為 -1
int maxDifference = -1;
// 遍歷每個數字i
for (int i = 0; i < nums.length - 1; i++) {
// 遍歷針對i右邊的所有數字j計算差值
for (int j = i + 1; j < nums.length; j++) {
int difference = nums[j] - nums[i];
// 只保留正差值
if (difference > 0) {
maxDifference = Math.max(maxDifference, difference);
}
}
}
return maxDifference;
}
}


丟去檢查。
https://ithelp.ithome.com.tw/upload/images/20240925/20169432NNuONf3QOX.png
因為今天好像中暑了,頭暈乎乎的,所以寫了題easy維持手感就好。


上一篇
day-9[medium.2048]next greater numerically balanced number
下一篇
day-11[medium.2017]grid game
系列文
轉生理工組後從零開始的leetcode刷題12
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言