Given an array nums, you are allowed to choose one element of
Return the minimum difference between the largest and smallest value of nums after performing at most 3 moves.
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 = { 1, 5, 0, 10, 14 };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(a, min(b, min(c, d)));}int main(){vector<int> nums = {1, 5, 0, 10, 14};cout << minDifference(nums);return 0;}
No comments:
Post a Comment