Similar Problems

Similar Problems not available

Minimum Score By Changing Two Elements - Leetcode Solution

Companies:

LeetCode:  Minimum Score By Changing Two Elements Leetcode Solution

Difficulty: Medium

Topics: greedy sorting array  

Problem Statement:

Given an integer array nums, find the minimum sum of elements after changing two elements at most. Each element can be changed to any value.

Example 1:

Input: nums = [1,2,3,4,5] Output: 10 Explanation: Change nums[4] and nums[3] to 1 and 2 respectively. Minimum sum is 1 + 2 + 1 + 2 + 5 = 11.

Solution:

To solve this problem, we need to find the two smallest elements in the array and replace them with any value to minimize the sum. There can be two cases:

Case 1: If there are at least two elements in the array.

In this case, we can find the first minimum element and second minimum element in the array. Then, we replace these two elements with any value and calculate the minimum sum of the updated array. Since we replace the smallest elements, the sum is minimized.

Example:

nums = [4,2,3,1,5]

First minimum = 1 Second minimum = 2

Replace 1 with 4 and 2 with 3

Updated array: [4,3,3,4,5]

Minimum sum = 4+3+3+4+5 = 19

Case 2: If there is only one element in the array.

In this case, the minimum sum is simply the value of the element.

Pseudo code:

  1. Initialize two variables min1 and min2 to maximum possible value.
  2. Traverse the array and for each element: a. If the element is smaller than min1, set min2 = min1 and min1 = element b. Else if the element is smaller than min2, set min2 = element
  3. If length of array is less than 2, return the only element.
  4. Else, return the sum of all the elements in the array except for min1 and min2, plus their replacement values.

Code in Python:

def minimumSum(nums: List[int]) -> int: min1 = min2 = float('inf') # Initializing to maximum possible value

for num in nums:
    if num < min1:
        min2 = min1
        min1 = num
    elif num < min2:
        min2 = num

if len(nums) < 2:
    return nums[0]
else:
    return sum(nums) - min1 - min2 + 2*min1 + 2*min2

Time Complexity: O(n)

Space Complexity: O(1)

Explanation:

We initialize two variables to maximum possible value as we need to find the minimum elements in the array. Then, we traverse the array and find the first minimum and second minimum elements. After this, we use the above discussed cases to find the minimum sum.

In the replacement formula, we add 2min1 and 2min2 as we are replacing two elements.

Minimum Score By Changing Two Elements Solution Code

1