By adding a 'max' and 'min' variable, we can make the solution's time complexity from O(n3) to O(n2):

    public long subArrayRanges(int[] nums) {
        long res = 0;
        for(int i=0;i<nums.length;i++){
            int max = nums[i], min=nums[i];
            for(int j=i+1;j<nums.length;j++){
                max = Math.max(max, nums[j]);
                min = Math.min(min, nums[j]);
                res+=max-min;
            }
        }
        return res;
    }

 

posted on 2022-03-22 05:19  阳光明媚的菲越  阅读(31)  评论(0编辑  收藏  举报