Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

2567. Minimum Score by Changing Two Elements

ArrayGreedySorting

Explanation:

To minimize the score after changing two elements, we need to update two elements in the array in such a way that the difference between the elements is minimized. We can achieve this by finding the maximum and minimum elements in the array and then calculating the difference between these elements. We then iterate through the array and try to find two elements where swapping them would result in a smaller difference.

Algorithmic Idea:

  1. Find the maximum and minimum elements in the array.
  2. Calculate the initial score based on the maximum and minimum elements.
  3. Iterate through the array and check if swapping any pair of elements results in a smaller score.
  4. Update the score accordingly.

Time Complexity:

The time complexity of this algorithm is O(N), where N is the number of elements in the array.

Space Complexity:

The space complexity of this algorithm is O(1), as we are not using any extra space apart from a few variables.

class Solution {
    public int minMoves(int[] nums) {
        int min = Integer.MAX_VALUE, max = Integer.MIN_VALUE;
        
        for (int num : nums) {
            min = Math.min(min, num);
            max = Math.max(max, num);
        }
        
        int initialScore = max - min;
        int newScore = initialScore;
        
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                int tempMax = Math.max(nums[i], nums[j]);
                int tempMin = Math.min(nums[i], nums[j]);
                newScore = Math.min(newScore, tempMax - tempMin);
            }
        }
        
        return newScore;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.