zoukankan      html  css  js  c++  java
  • 1330. 翻转子数组得到最大的数组值

    题目

    给你一个整数数组 nums 。「数组值」定义为所有满足 0 <= i < nums.length-1 的 |nums[i]-nums[i+1]| 的和。

    你可以选择给定数组的任意子数组,并将该子数组翻转。但你只能执行这个操作 一次 。

    请你找到可行的最大 数组值 。

    示例 1:

    输入:nums = [2,3,1,5,4]
    输出:10
    解释:通过翻转子数组 [3,1,5] ,数组变成 [2,5,1,3,4] ,数组值为 10 。
    示例 2:

    输入:nums = [2,4,9,24,2,1,10]
    输出:68

    提示:

    1 <= nums.length <= 3*10^4
    -10^5 <= nums[i] <= 10^5

    解答

    模拟策略

    根据题目的意思,翻转子数组之后其实只有子数组的边界值对整个数组的结果产生了影响,所以我们只需要计算对调边界值之后的变化量,再加到原始数组值就可以了。

    class Solution:
        def maxValueAfterReverse(self, nums: List[int]) -> int:
            max_change = 0
            for i in range(len(nums)-1):
                for j in range(len(nums)-1, i, -1):
                    if i == 0: # 第一个数的边界调换不发生变化
                        front_item = 0
                    else:
                        front_item = abs(nums[i-1] - nums[j]) - abs(nums[i-1] - nums[i])
                    if j == len(nums) - 1: # 最后一个数的边界调换不发生变化
                        back_item = 0
                    else:
                        back_item = abs(nums[i] - nums[j+1]) - abs(nums[j] - nums[j+1])
                    # 总的变化
                    total_change = front_item + back_item
                    if total_change > max_change:
                        max_change = total_change
            # 计算原来的数组值
            result = sum([abs(nums[i] - nums[i+1]) for i in range(len(nums)-1)])
    
            return result + max_change
    
  • 相关阅读:
    【UVa 1592】Database
    【UVa 400】Unix ls
    【UVa 136】Ugly Numbers
    【UVa 540】Team Queue
    【Uva 12096】The SetStack Computer
    【POJ 1050】To the Max
    【UVa 156】Ananagrams
    【UVa 10815】Andy's First Dictionary
    [HNOI/AHOI2018]转盘
    CF46F Hercule Poirot Problem
  • 原文地址:https://www.cnblogs.com/nomornings/p/13964828.html
Copyright © 2011-2022 走看看