20220226LeetCode刷题 增量元素之间最大差值 (使用前缀最小值方法)

给你一个下标从 0 开始的整数数组 nums ,该数组的大小为 n ,请你计算 nums[j] - nums[i] 能求得的 最大差值 ,其中 0 <= i < j < n 且 nums[i] < nums[j] 。

返回 最大差值 。如果不存在满足要求的 i 和 j ,返回 -1 。

 

示例 1:

输入:nums = [7,1,5,4]
输出:4
解释:
最大差值出现在 i = 1 且 j = 2 时,nums[j] - nums[i] = 5 - 1 = 4 。
注意,尽管 i = 1 且 j = 0 时 ,nums[j] - nums[i] = 7 - 1 = 6 > 4 ,但 i > j 不满足题面要求,所以 6 不是有效的答案。

class Solution {
    public int maximumDifference(int[] nums) {
        int result = -1;
        int n = nums.length;
        int permin = nums[0];
        for(int i = 1;i<n;i++) {
            if(nums[i] > permin) {
                result = Math.max(result,nums[i]-permin);
            }
            else {
                permin = nums[i];
            }
        }
        return result;
}
}

  

执行结果:
通过

添加备注

执行用时:0 ms, 在所有 Java 提交中击败了100.00%的用户
内存消耗:40.3 MB, 在所有 Java 提交中击败了32.13%的用户
通过测试用例:54 / 54
posted @ 2022-02-26 10:33  skystrivegao  阅读(45)  评论(0)    收藏  举报