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。
我的解題思路:
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;
}
}
丟去檢查。
因為今天好像中暑了,頭暈乎乎的,所以寫了題easy維持手感就好。