Minimum Difference Between Largest and Smallest Value in Three Moves

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 performing at most 3 moves.

Example 1:

Input: nums = [1,5,0,10,14]
Output: 1

Approach

Java

import java.util.Arrays;

public class MinDiffBetwValues {
    public static void main(String[] args) {
        int[] nums = { 1501014 };
        System.out.println(minDifference(nums));
    }

    static int minDifference(int[] nums) {
        Arrays.sort(nums);
        int n = nums.length;
        if (n <= 3)
            return 0;
        int a = nums[n - 4] - nums[0];
        int b = nums[n - 1] - nums[3];
        int c = nums[n - 2] - nums[2];
        int d = nums[n - 3] - nums[1];
        return Math.min(a, Math.min(b, Math.min(c, d)));
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

int minDifference(vector<int&nums)
{
    sort(nums.begin(), nums.end());
    int n = nums.size();
    if (n <= 3)
        return 0;
    int a = nums[n - 4] - nums[0];
    int b = nums[n - 1] - nums[3];
    int c = nums[n - 2] - nums[2];
    int d = nums[n - 3] - nums[1];
    return min(amin(bmin(cd)));
}

int main()
{
    vector<intnums = {1501014};
    cout << minDifference(nums);
    return 0;
}


No comments:

Post a Comment