LintCode 1859: Minimum Amplitude

  1. Minimum Amplitude

Given an array A consisting of N integers. In one move, we can choose any element in this array and replace it with any value.
The amplitude of an array is the difference between the largest and the smallest values it contains.
Return the smallest amplitude of array A that we can achieve by performing at most three moves

Example
Example 1
Input:
A = [-9, 8, -1]
Output: 0
Explanation: We can replace -9 and 8 with -1 so that all element are equal to -1, and then the amplitude is 0
Example 2:
Input:
A = [14, 10, 5, 1, 0]
Output: 1
Explanation: To achieve an amplitude of 1, we can replace 14, 10 and 5 with 1 or 0.
Example 3:
Input:
A = [11, 0, -6, -1, -3, 5]
Output: 3
Explanation: This can be achieved by replacing 11, -6 and 5 with three values of -2.
Notice
N is an integer within the range: [2, 10000]
each element of array A is an integer within the range: [-50, 50]

解法1:

class Solution {
public:
    /**
     * @param A: a list of integer
     * @return: Return the smallest amplitude
     */
    int MinimumAmplitude(vector<int> &A) {
        int n = A.size();
        if (n <= 4) return 0;
        sort(A.begin(), A.end());
        
        int option1 = A[n - 4] - A[0];
        int option2 = A[n - 3] - A[1];
        int option3 = A[n - 2] - A[2];
        int option4 = A[n - 1] - A[3];
        
        return min(option1, min(option2, min(option3, option4)));
    }
};

解法2:

class Solution {
public:
    /**
     * @param A: a list of integer
     * @return: Return the smallest amplitude
     */
    int MinimumAmplitude(vector<int> &A) {
        // write your code here
        int n = A.size();
        if(n <= 4) return 0;

        sort(A.begin(), A.end());
        
        int mmin = INT_MAX;
        for(int i = 0;i < 4;i++){
            mmin = min(mmin, A[n - 3 + i - 1] - A[i]);
        } 
        return mmin;
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值