[leetCode]1330.翻转子数组得到最大的数组值

在这里插入图片描述

class Solution {
    public int maxValueAfterReverse(int[] nums) {
        int n = nums.length;
        int raw = sum(nums);//计算未翻转时的数组值
        int delta = 0;
        //处理两个边界条件
        for(int r = 0; r < n-1; r++){
            delta = Math.max(delta, Math.abs(nums[0]-nums[r+1])-Math.abs(nums[r]-nums[r+1]));
        }
        for(int l = 0; l < n - 1; l++){
            delta = Math.max(delta, Math.abs(nums[l]-nums[n-1])-Math.abs(nums[l]-nums[l+1]));
        }
        //计算其余情况
        for(int r = 2; r < n-1; r++){
            for(int l = 1; l < r; l++){
                delta = Math.max(delta, (Math.abs(nums[l]-nums[r+1])+Math.abs(nums[l-1]-nums[r]))
                                    - (Math.abs(nums[l-1]-nums[l])+Math.abs(nums[r]-nums[r+1])) );
            }
        }
        return raw + delta;
    }

    private int sum(int[] nums){
        int sum = 0;
        for(int i=0; i < nums.length - 1; i++){
            sum+= Math.abs(nums[i] - nums[i+1]);
        }
        return sum;
    }
}

去绝对值

class Solution {
    public int maxValueAfterReverse(int[] nums) {
        int n = nums.length;
        int raw = sum(nums);//计算未翻转时的数组值
        int delta = 0;
        //处理两个边界条件
        for(int r = 0; r < n-1; r++){
            delta = Math.max(delta, Math.abs(nums[0]-nums[r+1])-Math.abs(nums[r]-nums[r+1]));
        }
        for(int l = 0; l < n - 1; l++){
            delta = Math.max(delta, Math.abs(nums[l]-nums[n-1])-Math.abs(nums[l]-nums[l+1]));
        }
        int[] dp = new int[4];
        Arrays.fill(dp,Integer.MIN_VALUE); 
        for(int i = 1; i < n; i++){
            int x = Math.abs(nums[i-1] - nums[i]);
            dp[0]=Math.max(dp[0],nums[i]-nums[i-1]-x);
            dp[1]=Math.max(dp[1],-nums[i]-nums[i-1]-x);
            dp[2]=Math.max(dp[2],nums[i]+nums[i-1]-x);
            dp[3]=Math.max(dp[3],-nums[i]+nums[i-1]-x); 
        }
        delta = Math.max(delta,Math.max(dp[0]+dp[3],dp[1]+dp[2]));
        return raw + delta;
    }

    private int sum(int[] nums){
        int sum = 0;
        for(int i=0; i < nums.length - 1; i++){
            sum+= Math.abs(nums[i] - nums[i+1]);
        }
        return sum;
    }
}
posted @ 2020-07-30 14:07  消灭猕猴桃  阅读(245)  评论(0编辑  收藏  举报