当前位置:网站首页>2016. maximum difference between incremental elements

2016. maximum difference between incremental elements

2022-06-13 03:25:00 Python's path to becoming a God

  1. The maximum difference between incremental elements
    I'll give you a subscript from 0 The starting array of integers nums , The size of the array is n , Please calculate nums[j] - nums[i] Obtainable Maximum difference , among 0 <= i < j < n And nums[i] < nums[j] .

return Maximum difference . If there is no... That meets the requirements i and j , return -1 .

Example 1:

 Input :nums = [7,1,5,4]
 Output :4
 explain :
 The maximum difference appears in  i = 1  And  j = 2  when ,nums[j] - nums[i] = 5 - 1 = 4 .
 Be careful , Even though  i = 1  And  j = 0  when  ,nums[j] - nums[i] = 7 - 1 = 6 > 4 , but  i > j  Does not meet the requirements of the problem surface , therefore  6  Not a valid answer .

Example 2:

 Input :nums = [9,4,3,2]
 Output :-1
 explain :
 There is no simultaneous satisfaction  i < j  and  nums[i] < nums[j]  Of these two conditions  i, j  Combine .

Example 3:

 Input :nums = [1,5,2,10]
 Output :9
 explain :
 The maximum difference appears in  i = 0  And  j = 3  when ,nums[j] - nums[i] = 10 - 1 = 9 .
class Solution {
public:
    int maximumDifference(vector<int>& nums) {
        int len = nums.size();
        vector<int> dp(len, 0);
        int cost = nums[0];
        for(int i = 1; i < len; ++i){
            cost = min(cost, nums[i]);
            dp[i] = max(dp[i - 1], nums[i] - cost);
        }
        return dp[len - 1] > 0 ? dp[len - 1] : -1;
    }
};

原网站

版权声明
本文为[Python's path to becoming a God]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202280530515751.html