leetcode1509 Minimum Difference Between Largest and Smallest Value in Three Moves

161 篇文章 0 订阅

题目:

Given an array nums, you are allowed to choose one element of nums and change it by any value in one move.

Return the minimum difference between the largest and smallest value of nums after perfoming at most 3 moves.

 

Example 1:

Input: nums = [5,3,2,4]
Output: 0
Explanation: Change the array [5,3,2,4] to [2,2,2,2].
The difference between the maximum and minimum is 2-2 = 0.

Example 2:

Input: nums = [1,5,0,10,14]
Output: 1
Explanation: Change the array [1,5,0,10,14] to [1,1,0,1,1]. 
The difference between the maximum and minimum is 1-0 = 1.

Example 3:

Input: nums = [6,6,0,1,1,4,6]
Output: 2

Example 4:

Input: nums = [1,5,6,14,15]
Output: 1

Constraints:

  • 1 <= nums.length <= 10^5
  • -10^9 <= nums[i] <= 10^9

算法解析:

首先对数组里面进行排序,那么在不改变数字的情况下,最大的差值为nums[0] - nums[nums.size()-1]

那么,在改变三个值的情况下,改变的是前缀和后缀,有以下几种情况:

     前缀:0     后缀:3         nums[n - 1 - 3] - nums[0]

     前缀:1     后缀:2         nums[n - 1 - 2] - nums[1]

     前缀:2     后缀:1         nums[n - 1 - 1] - nums[2]

     前缀:3     后缀:0         nums[n - 1] - nums[3]

代码如下:

class Solution {
public:
    int minDifference(vector<int>& nums) {
        int n = nums.size();
        if(n <= 3)    return 0;
        sort(nums.begin(),nums.end());
        int res = INT_MAX;
        for(int i = 0, j = 3; i <= 3; i++,j--)
        {
            res = min(res,nums[n - 1 - j] - nums[i]);
        }
        return res;
    }
};

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值