question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
minimum-score-by-changing-two-elements
[Python] ✅🔥 2-line Solution w/ Explanation!
python-2-line-solution-w-explanation-by-8mz2y
Please upvote/favourite/comment if you like this solution!\n\n# Approach\n Describe your approach to solving the problem. \nThis question reduces to minimizing
j-douglas
NORMAL
2023-02-18T16:11:48.681658+00:00
2023-02-18T17:59:01.361014+00:00
404
false
## **Please upvote/favourite/comment if you like this solution!**\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThis question reduces to minimizing the range of `nums` by changing 2 elements in `nums`. We can minimize the range by doing one of 3 options:\n1. Increase the smallest two numbers. Therefore, the range in this option will be `largest - third smallest`.\n2. Increase the smallest number and decrease the largest number. Therefore, the range in this option will be `second largest - second smallest`.\n3. Decrease the largest two numbers. Therefore, the range in this option will be `third largest - smallest`.\n\nWe return the minimum of these three options to find the minimum score possible.\n\n# Code\n```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n nums.sort()\n return min(nums[-1]-nums[2],nums[-2]-nums[1],nums[-3]-nums[0]) \n```\n\n# Complexity\n- Time complexity: $$O(n \\log n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->
8
0
['Math', 'Sorting', 'Python', 'Python3']
1
minimum-score-by-changing-two-elements
Simple java solution
simple-java-solution-by-siddhant_1602-y85i
\n# Complexity\n- Time complexity: O(n log n)\n\n- Space complexity: O(1)\n\n# Code\n\nclass Solution {\n public int minimizeSum(int[] nums) {\n Array
Siddhant_1602
NORMAL
2023-02-18T16:03:05.374610+00:00
2023-02-18T16:24:11.279792+00:00
442
false
\n# Complexity\n- Time complexity: $$O(n log n)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n Arrays.sort(nums);\n int a=nums[nums.length-1]-nums[0];\n int b=nums[nums.length-1]-nums[2];\n int c=nums[nums.length-3]-nums[0];\n int d=nums[nums.length-2]-nums[1];\n return Math.min(a,Math.min(b,Math.min(c,d)));\n }\n}\n```
8
0
['Sorting', 'Java']
0
minimum-score-by-changing-two-elements
Sorting || Two liner || Easy & Understandable C++ Code
sorting-two-liner-easy-understandable-c-h1x4b
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
vidit987
NORMAL
2023-02-18T16:13:08.404137+00:00
2023-02-18T16:18:02.523776+00:00
272
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>&v) {\n int i,n=v.size();\n sort(v.begin(),v.end());\n return min({v[n-1]-v[2],v[n-3]-v[0],v[n-2]-v[1]});\n }\n};\n```
7
0
['C++']
0
minimum-score-by-changing-two-elements
O(N) TC - O(1) SC || 100% Beats || Most Efficient Approach || C++ Solution
on-tc-o1-sc-100-beats-most-efficient-app-pnm5
Intuition\nThere Is No Need Of Sorting Here , By the Observation Of Some Random Test Cases i got know that, we just need to keep track first 3 minimum elements
brucewayne_5
NORMAL
2023-05-31T08:20:57.002158+00:00
2023-05-31T08:20:57.002202+00:00
254
false
# Intuition\nThere Is No Need Of Sorting Here , By the Observation Of Some Random Test Cases i got know that, we just need to keep track first 3 minimum elements and first 3 maximum elements . then apply the appropriate conditions to get the answer.\n# Approach\n**1 Condition**\nConsider the array : [1,4,5,6,7,8]\nNow the optimal solution in this case is changing \nchanging 1 , 4 to 5\nNow the array becomes [5,5,5,6,7,8].\nNow the answer is |5-5 | + | 8-5 | =3.\nif you observe carefully the answer is simply the difference between \nfirst maximum element and the third minimum element.\n**2 Condition**\nConsider the array : [8,28,42,58,75]\nNow the optimal solution in this case is changing \nchanging 8 to 42 and 75 to 42\nNow the array becomes [42,28,42,58,42].\nNow the answer is |42-42 | + |58 - 28 | =30.\nif you observe carefully the answer is simply the difference between \nsecond maximum element and the second minimum element.\n**3 Condition**\nConsider the array : [9,27,33,59,81]\nNow the optimal solution in this case is changing \nchanging 51 to 33 and 81 to 33\nNow the array becomes [9,27,33,33,33].\nNow the answer is |33-33 | + |33 - 9 | =24.\nif you observe carefully the answer is simply the difference between \nthird maximum element and the first minimum element.\n\nSO THE ANSWER LIES ON THESE THREE CONDITIONS ONLY , SO FIND FIRST 3 MINIMUM ELEMENT AND FIRST 3 MAXIMUM ELEMENTS THEN RETURN THE RESULT.\n\n\n# Complexity\n- Time complexity:\nO(N)\n- Space complexity:\nO(1)\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int min1=1e9,min2=1e9,min3=1e9,maxi1=0,maxi2=0,maxi3=0;\n for(auto i:nums)\n {\n if(i<min1){ min3=min2;min2=min1;min1=i; }\n else if(i<min2) { min3=min2, min2=i;}\n else if(i<min3) min3=i;\n if(i>maxi1) { maxi3=maxi2,maxi2=maxi1 ,maxi1=i;}\n else if(i>maxi2) {maxi3=maxi2,maxi2=i;}\n else if(i>maxi3) maxi3=i;\n }\n return min(maxi1-min3,min(abs(maxi2-min2),maxi3-min1));\n }\n};\n```
6
0
['Greedy', 'C++']
0
minimum-score-by-changing-two-elements
Video Solution - [With Sorting, Easy to Understand] - C++
video-solution-with-sorting-easy-to-unde-u7lz
Video Solution\nhttps://youtu.be/B3iSW6gKXXk\n\n# Code\n\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int n = nums.size();\n
aryan_0077
NORMAL
2023-02-18T17:45:28.735517+00:00
2023-02-18T17:45:28.735550+00:00
228
false
# Video Solution\nhttps://youtu.be/B3iSW6gKXXk\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int n = nums.size();\n \n sort(nums.begin(), nums.end());\n \n int ans = min( min( nums[n-1] - nums[2] , nums[n-3] - nums[0] ) , nums[n-2] - nums[1]);\n \n return ans;\n }\n};\n```
6
0
['C++']
1
minimum-score-by-changing-two-elements
Easy Peasy C++ code | O(n logn) time complexity | O(1) Space Complexity
easy-peasy-c-code-on-logn-time-complexit-qab6
Complexity\n- Time complexity:\nO(n logn) for sorting the vector\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n int minimizeSum(vector
karankc23
NORMAL
2023-02-18T18:26:13.503138+00:00
2023-02-18T18:26:13.503175+00:00
838
false
# Complexity\n- Time complexity:\nO(n logn) for sorting the vector\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& a) {\n int n = a.size();\n if(n==3){\n return 0;\n }\n sort(a.begin(),a.end());\n int one = a[n-1] - a[2];\n int two = a[n-3] - a[0];\n int three = a[n-2] - a[1];\n return min({one,two,three});\n }\n};\n```
5
0
['C++']
2
minimum-score-by-changing-two-elements
[C++] 2 Liner Code
c-2-liner-code-by-pathak_ankit-6h1j
Self-explanatory\nOnly three windows are possible to minimze\n# Code\n\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) \n {\n \n
Pathak_Ankit
NORMAL
2023-02-18T16:11:39.547318+00:00
2023-02-18T16:13:28.085939+00:00
745
false
Self-explanatory\nOnly three windows are possible to minimze\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) \n {\n \n int n=nums.size();\n sort(nums.begin(),nums.end());\n return min({nums[n-3]-nums[0],nums[n-2]-nums[1],nums[n-1]-nums[2]});\n \n }\n};\n```
5
0
['C++']
0
minimum-score-by-changing-two-elements
Simple c++ Easiest solution with 3 cases
simple-c-easiest-solution-with-3-cases-b-9f09
Intuition\nSort the vector to focus mainly on minimum and maximum values.\nFind the cases where we can minimize the score\nMinimum diff can always be made 0 by
sanjaygouroju
NORMAL
2023-02-18T16:01:37.393085+00:00
2023-02-24T17:33:59.423200+00:00
405
false
# Intuition\nSort the vector to focus mainly on minimum and maximum values.\nFind the cases where we can minimize the score\nMinimum diff can always be made 0 by making two elements equal.\nTo minimize the maximum diff there can be\nthree cases possible:\n1. First and last element can be made equal to its adjacent value. So, the max diff becomes v[v.size()-2]-v[1] (bcuz we make v[0]=v[1] & v[v.size()-1]=v[v.size()-2])\n2. First 2 elements can be made equal to 3rd elemnt.So, the max diff becomes v[v.size()-1]-v[2] (bcuz we make v[0]=v[1]=v[2])\n3. Last 2 elements can be made equal to last but 3rd element. So, the max diff becomes v[v.size()-3]-v[0] (bcuz we make v[v.size()-1]=v[v.size()-2]=v[v.size()-3])\n\n# Complexity\n- Time complexity: O(nlog(n))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& v) {\n sort(v.begin(),v.end());\n/*\n1st case score: v[v.size()-2]-v[1]+0\n2st case score: v[v.size()-1]-v[2]+0\n3st case score: v[v.size()-3]-v[0]+0\n*/\n return min(min(v[v.size()-2]-v[1] ,v[v.size()-1]-v[2]),v[v.size()-3]-v[0]);\n }\n};\n```
5
0
['C++']
1
minimum-score-by-changing-two-elements
Simplest Java solution with Time and Space complexity explaination
simplest-java-solution-with-time-and-spa-apfb
Approach\n Describe your approach to solving the problem. \nThe code first checks if the length of the input array is 3, and if so, returns 0. This is because,
BleedBlue38
NORMAL
2023-02-18T18:55:56.078443+00:00
2023-02-18T18:55:56.078478+00:00
838
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe code first checks if the **length of the input array is 3**, and if so, **returns 0.** This is because, in this case, *all elements in the array can be made equal by replacing any two elements with the third element, and hence, the sum of differences will be 0.*\nThen, the code sorts the input array using the Arrays.sort() method, which sorts the elements of the array in ascending order.\n\nAfter sorting, the code calculates three possible values for the minimized sum of absolute differences, by removing any two elements and replacing them with any element from the remaining elements in the array:\n\n- A : **removing the first two elements of the sorted array** and replacing them with any element in the middle of the array, and then calculating the absolute difference between the maximum element and the minimum element in the resulting array.\n- B : **removing the last two elements of the sorted array** and replacing them with any element in the middle of the array, and then calculating the absolute difference between the maximum element and the minimum element in the resulting array.\n- C : **removing the first and last elements of the sorted array** and replacing them with any element in the middle of the array, and then calculating the absolute difference between the maximum element and the minimum element in the resulting array.\n\nFinally, the code returns the minimum value of a, b, and c using the Math.min() method. This value represents the minimized sum of absolute differences between all pairs of elements in the input array that can be achieved by removing any two elements and replacing them with any element from the remaining elements in the array.\n\n# Complexity\n- ***Time complexity:***\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nThe time complexity of this code is ***O(nlogn)***, where n is the length of the input array nums.\n\nThis is because the code first *sorts the input array* using Arrays.sort(nums), which has a time complexity of O(nlogn) for an array of length n.\n\nThen, the code calculates three possible values for the minimized sum of absolute differences by performing some simple arithmetic operations, which take constant time.\n\nFinally, the code returns the minimum value of the three possible values using the Math.min() method, which also takes constant time.\n\nTherefore, ***the overall time complexity of this code is dominated by the time complexity of sorting the input array, which is O(nlogn).***\n\n- ***Space complexity:***\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n**The space complexity of this code is O(1)**, which means that it uses a constant amount of extra space regardless of the size of the input array nums.\n\nThe only extra space used in this code are the integer **variables a, b, and c,** which store the three possible values of the minimized sum of absolute differences. These variables take a **constant amount of space** and do not depend on the size of the input array.\n\nIn addition, the Arrays.sort(nums) method sorts the input array in-place, without creating a new array, so it does not increase the space complexity of the code.\n\n***Therefore, the space complexity of this code is O(1).***\n\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n \n //because you can make any two elements equal to the third element and hence the array will have all elements equal and so the diffrence will be 0 for all pairs\n \n if(nums.length==3){\n return 0;\n }\n \n Arrays.sort(nums);\n \n //remove first two i.e replacing first two elements with any element in between the array\n int a=nums[nums.length-1]-nums[2];\n \n //remove last two i.e replacing last two elements with any element in between the array\n int b=nums[nums.length-3]-nums[0];\n \n //remove last and first i.e replacing first and last elements with any element in between the array\n int c=nums[nums.length-2]-nums[1];\n \n return Math.min(a,Math.min(b,c));\n \n \n }\n}\n```
4
0
['Java']
0
minimum-score-by-changing-two-elements
Python
python-by-abdulazizms-4zqc
\n# Code\n\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n nums.sort()\n return min(nums[-2] - nums[1],\n
abdulazizms
NORMAL
2023-02-18T16:19:59.312041+00:00
2023-02-18T16:19:59.312082+00:00
400
false
\n# Code\n```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n nums.sort()\n return min(nums[-2] - nums[1],\n nums[-1] - nums[2],\n nums[-3] - nums[0])\n \n```
4
0
['Python3']
2
minimum-score-by-changing-two-elements
Java | 2-3 Lines | Sorting
java-2-3-lines-sorting-by-aaveshk-f5a2
Observations\nIf two numbers are equal, low is 0. We\'ll use this to remove low from consideration \nThere are three possibilities to minimize score:\n1. Set le
aaveshk
NORMAL
2023-02-18T16:01:05.651670+00:00
2023-02-18T16:15:12.762231+00:00
664
false
**Observations**\nIf two numbers are equal, low is 0. We\'ll use this to remove `low` from consideration \nThere are three possibilities to minimize score:\n1. Set least two elements as third least\n2. Set greatest two elements as third greatest\n3. Set least to second least and greatest to second greatest\n\n```\nclass Solution\n{\n public int minimizeSum(int[] nums)\n {\n Arrays.sort(nums);\n return Math.min(Math.min(nums[nums.length-1]-nums[2],nums[nums.length-3]-nums[0]),nums[nums.length-2] - nums[1]);\n }\n}\n```\nReadable:\n```\nclass Solution\n{\n public int minimizeSum(int[] nums)\n {\n Arrays.sort(nums);\n int n = nums.length;\n return Math.min(Math.min(nums[n-1]-nums[2] , nums[n-3]-nums[0]), nums[n-2] - nums[1]);\n }\n}\n```
4
1
['Java']
1
minimum-score-by-changing-two-elements
USING SORT || C++ || EASY TO UNDERSTAND
using-sort-c-easy-to-understand-by-ganes-g9s2
Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n int minimizeSum(vector<int>& v) {\n sor
ganeshkumawat8740
NORMAL
2023-05-19T11:53:28.754618+00:00
2023-05-19T11:53:28.754667+00:00
498
false
# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& v) {\n sort(v.begin(),v.end());\n return min({v[v.size()-3]-v[0],v[v.size()-2]-v[1],v[v.size()-1]-v[2]});\n }\n};\n```
3
0
['Array', 'Greedy', 'Sorting', 'C++']
0
minimum-score-by-changing-two-elements
JavaScript solution
javascript-solution-by-svolkovichs-rx9i
Intuition\nThe answer will be in one of 3 cases. We set Max and second Max elements to third Max. We set Min and second Min elements to third Min element. We se
svolkovichs
NORMAL
2023-02-19T23:17:17.309739+00:00
2023-02-19T23:17:17.309769+00:00
86
false
# Intuition\nThe answer will be in one of 3 cases. We set Max and second Max elements to third Max. We set Min and second Min elements to third Min element. We set Max to second Max and Min to second Min.\n\n# Approach\nTo simplify the code we sort the array. The answer will be the following Math.min(nums[end-2]-nums[0], nums[end-1]-nums[1], nums[end]-nums[2])\n\n# Complexity\n- Time complexity:\nO(N*log(N))\n\n- Space complexity:\nO(1)\n\n# Code\n```\n/**\n * @param {number[]} nums\n * @return {number}\n */\nvar minimizeSum = function(nums) { \n let arr = nums.sort((a,b) => a - b);\n let end = nums.length -1;\n \n return Math.min(nums[end-2]-nums[0], nums[end-1]-nums[1], nums[end]-nums[2]);\n};\n```
3
0
['JavaScript']
1
minimum-score-by-changing-two-elements
✅C++ | ✅Intuitive Approach
c-intuitive-approach-by-yash2arma-oosn
Intuition\nTo get minimum score either we need to make smallest element as larget or largest element as smallest in the array.\n\n# Approach\nWe have three case
Yash2arma
NORMAL
2023-02-19T15:18:10.118023+00:00
2023-02-19T15:41:01.851146+00:00
266
false
# Intuition\nTo get minimum score either we need to make smallest element as larget or largest element as smallest in the array.\n\n# Approach\nWe have three cases by which we can get minimum score\n## Case-1:\nWe can make first two elements as maximum element.\n**Example-**\n[1,4,7,8,5]\n[1,4,5,7,8] (sorted)\n[8,8,5,7,8] (applied case-1)\nScore = (8-5)-(8-8) = 3\n\n## Case-2:\nWe can make last two elements as minimum element.\n**Example-**\n[1,4,3]\n[1,3,4] (sorted)\n[1,1,1]\nScore = (1-1)-(1-1)=0\n\n## Case-3:\nWe can make 1st and last position element as 2nd minimum element or 2nd maximum element.\n**Example-**\n[58,42,8,75,28]\n[8,28,42,58,75] (sorted)\n[28,28,42,58,28]\nScore = (58-28)-(28-28)=30\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution \n{\npublic:\n int minimizeSum(vector<int>& nums) \n {\n int n=nums.size();\n sort(nums.begin(), nums.end());\n \n //case-1 make first two elements as maximum element \n int high1 = nums[n-1] - nums[2]; \n \n //case-2 make last two elements as minimum element\n int high2 = nums[n-3] - nums[0];\n \n //case-3 make 1st and last position element as 2nd minimum element or 2nd maximum element\n int high3 = nums[n-2] - nums[1];\n \n return min({high1, high2, high3}); \n }\n};\n```\n\n# Please upvote if you like this approach
3
0
['Array', 'Math', 'Sorting', 'C++']
0
minimum-score-by-changing-two-elements
ONE LINE CODE || C++
one-line-code-c-by-yash___sharma-t115
\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n return min({nums[nums.size()-1]-nums[2],n
yash___sharma_
NORMAL
2023-02-19T04:39:54.566394+00:00
2023-02-19T04:39:54.566434+00:00
79
false
```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n return min({nums[nums.size()-1]-nums[2],nums[nums.size()-3]-nums[0],nums[nums.size()-2]-nums[1]});\n }\n};\n```
3
0
['Math', 'Greedy', 'C', 'Sorting', 'C++']
0
minimum-score-by-changing-two-elements
Easiest C++ Solution (5 line code) - Very Easy
easiest-c-solution-5-line-code-very-easy-20wx
Intuition\nThere can only be 3 cases, either \n- Change the first 2 elements\n- We change the last 2 elements\n- We change the 1st and the last element\n\n# App
mihir_sahai
NORMAL
2023-02-18T18:01:46.799709+00:00
2023-03-05T08:48:45.416051+00:00
47
false
# Intuition\nThere can only be 3 cases, either \n- Change the first 2 elements\n- We change the last 2 elements\n- We change the 1st and the last element\n\n# Approach\nWe sort the given array, then we can calculate all the 3 cases just by considering the difference between the mentioned values.\nAlso, we don\'t need a seperate calculation for \'low\', since we will always replace the choosen values with the same values.\n\n# Complexity\n- Time complexity:\nO(n*log(n))\n\n- Space complexity:\nO(1)\n\n# Code\n```\nint minimizeSum(vector<int>& v) {\n int ans=INT_MAX;\n int n=v.size();\n sort(v.begin(),v.end());\n ans=min(ans,v[n-1]-v[2]);\n ans=min(ans,v[n-3]-v[0]);\n ans=min(ans,v[n-2]-v[1]);\n return ans;\n }\n```
3
0
['C++']
0
minimum-score-by-changing-two-elements
C++ || Easy
c-easy-by-shrikanta8-wjyh
\n# Code\n\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n\n sort(nums.begin(), nums.end());\n int n= nums.size();\n
Shrikanta8
NORMAL
2023-02-18T16:01:24.900279+00:00
2023-02-18T16:04:56.205385+00:00
62
false
\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n\n sort(nums.begin(), nums.end());\n int n= nums.size();\n \n int val = min (abs(nums[0] - nums[n-3]) , min( abs(nums[n-2]-nums[1]), abs(nums[2] - nums[n-1] ) ) );\n return val;\n }\n};\n```
3
0
['C++']
0
minimum-score-by-changing-two-elements
Beginner friendly
beginner-friendly-by-ng6-3n3k
\n\n# Code\n\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n i
ng6
NORMAL
2023-05-02T17:10:22.079906+00:00
2023-05-02T17:10:22.079952+00:00
31
false
\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n int case1=nums[n-3]-nums[0];//change two of largest to the third largest\n int case2=nums[n-1]-nums[2];//change two of smallest to the third smallest\n int case3=nums[n-2]-nums[1];//change the smallest to next smallest and greatest to prev greatest \n return min(case1,min(case2,case3));\n }\n};\n\n```
2
0
['Sorting', 'C++']
0
minimum-score-by-changing-two-elements
✅ 2 Lines of Code || Explaination💯
2-lines-of-code-explaination-by-razpatel-512c
First we will sort the list so we can easily access minimum and maximum values.\n\nThere are total 3 ways in which we can get answer.\n1. By changing First two
RazPatel
NORMAL
2023-02-21T04:40:10.484005+00:00
2023-02-21T06:31:25.203720+00:00
104
false
First we will sort the list so we can easily access minimum and maximum values.\n\nThere are total 3 ways in which we can get answer.\n1. By changing First two values - In this case we will chage first two values to make difference zero. Now lowest value we have is nums[2] and largest is nums[-1].\n2. By changing Last two values - In this case we will chage last two values to to make difference zero. Now lowest value we have is nums[0] and largest is nums[-3].\n3. By changing Last value and First Values - In this case we will chage first value and last value to make difference zero. Now lowest value is nums[1] and largest is nums[-2].\n\nWe will select minimum from this three values.\n\n**Plot - We really dont need two change these values, we will calculate difference between values in which we are interested.**\n# Code\n```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n nums.sort()\n return min(nums[-1] - nums[2], nums[-2] - nums[1], nums[-3] - nums[0])\n \n \n```
2
0
['Python3']
0
minimum-score-by-changing-two-elements
Python short and clean. Beats 100%. 2 solutions. Sorting and Heap.
python-short-and-clean-beats-100-2-solut-slti
Approach 1: Sort\n1. Sort nums to s_nums for random access to maxes and mins.\n\n2. If there were 0 changes allowed:\n There\'s nothing to do.\n The best
darshan-as
NORMAL
2023-02-19T11:08:26.857614+00:00
2023-02-19T11:09:05.194978+00:00
267
false
# Approach 1: Sort\n1. Sort `nums` to `s_nums` for random access to maxes and mins.\n\n2. If there were `0` changes allowed:\n There\'s nothing to do.\n The best we can do is: `s_nums[n - 1] - s_nums[0]`.\n \n Note: Abbriviating `s_num[a] - s_num[b]` as `|a, b|` from henceforth.\n Hence the above becomes `|n - 1, 0|`\n\n3. If there were `1` change allowed:\n We can change the first or the last number to the adjacent one.\n The best we can do is:\n `min(|n - 1, 1| (changing the first), |n - 2, 0| (changing the last)`.\n\n4. If there were `2` change allowed:\n The best we can do is:\n `min(|n - 1, 2|, |n - 2, 1|, |n - 3, 0|)`\n\n5. Extending the same, If there were `k` changes allowed:\n The best we can do is:\n `min(|n - 1, k|, |n - 2, k - 1|, ...., |n - k - 1, 0|)`\n\n# Complexity\n- Time complexity: $$O(n * log(n))$$\n\n- Space complexity: $$O(n)$$\n\nwhere, `n is the length of nums`.\n\n# Code\n```python\nclass Solution:\n def minimizeSum(self, nums: list[int]) -> int:\n s_nums = sorted(nums)\n k = 2\n return min(\n s_nums[i] - s_nums[j]\n for i, j in zip(range(-1, -k - 2, -1), range(k, -1, -1))\n )\n\n\n```\n\n---\n\n# Approach 2: Heap\nSince we only need first `k` minimum and first `k` maximum elements in `nums`, given atmost `k` changes allowed, we can use a `min heap` and `max heap` respectively.\n\nThis allows to reduce the time complexity from $$n + n * log(n)$$ to $$n + k * log(n)$$.\n\n# Complexity\n- Time complexity: $$O(n + k * log(n))$$\nFor given question, `k = 2`, `=>` $$O(n)$$\n\n- Space complexity: $$O(n)$$\n\nwhere,\n`n is the length of nums`,\n`k is the number of number of values that can be changed`.\n\n# Code\n```python\nclass Solution:\n def minimizeSum(self, nums: list[int]) -> int:\n k, n = 2, len(nums)\n min_hq, max_hq = list(nums), list(map(neg, nums))\n heapify(min_hq); heapify(max_hq)\n\n maxs = tuple(-heappop(max_hq) for _ in range(min(k + 1, n)))\n mins = tuple( heappop(min_hq) for _ in range(min(k + 1, n)))\n\n return min(map(sub, maxs, reversed(mins)))\n\n\n```
2
0
['Math', 'Sorting', 'Heap (Priority Queue)', 'Python', 'Python3']
0
minimum-score-by-changing-two-elements
Greedy Kotlin Lambda O(N log N)
greedy-kotlin-lambda-on-log-n-by-kotlinc-91jn
Consider the sorted scenario, where the index of the nums is\n0 1 2 3 4 .... n-3, n-2, n-1\nWe need to find the min value of\n nums[n-1] vs nums[2]\n nums[n-2]
kotlinc
NORMAL
2023-02-18T20:44:01.682321+00:00
2023-08-27T18:34:28.921871+00:00
30
false
Consider the sorted scenario, where the index of the nums is\n```0 1 2 3 4 .... n-3, n-2, n-1```\nWe need to find the min value of\n* `nums[n-1]` vs `nums[2]`\n* `nums[n-2]` vs `nums[1]`\n* `nums[n-3]` vs `nums[0]`\nThe commonality is `n-1-2 = n-3`, `n-2-1 = n-3` and `n-3-0 = n-3`. So we write the following lambda to find the `nums[n-3+it]` vs `nums[it]`\n\n```kotlin\nclass Solution {\n fun minimizeSum(nums: IntArray): Int {\n nums.sort()\n return (0 until 3).map {\n nums[nums.size - 3 + it] - nums[it]\n }.minOrNull()!!\n }\n}\n```\n
2
0
['Kotlin']
0
minimum-score-by-changing-two-elements
Java solution with detailed explanation
java-solution-with-detailed-explanation-c9ae5
Intuition\nSince we can change the value of atmost 2 elements, we are left with three choices, I will explain why these three choices only.\n\nWe know the max s
kunal-j
NORMAL
2023-02-18T16:22:42.233153+00:00
2023-02-18T16:22:42.233185+00:00
68
false
# Intuition\nSince we can change the value of atmost 2 elements, we are left with three choices, I will explain why these three choices only.\n\nWe know the max score we can achieve is by subtracting the min element from the max element.\nNow we are given a condition that we can change atmost two values, and so we can reduce the min score to 0(always) by choosing any two numbers are setting them to same value, so the problem boils down to simply reduce the max score which is (arr[max_Index] - arr[min_Index])\n\nNow we have three choices:\n\nFirst: we decide to change the value of first two minimum elements of the array to the third one and then calculate the score.\n\nSecond: we decide to change the value of first two maxmium elements of the array to the third one and then calculate the score.\n\nThird: we decide to change the value of minimum element to 2nd minimum element and the value of first maximum element to 2nd maximum element and then we calculate score.\n\nThen we will return the min of all the three choices\n\nThe reason we did this was because we know that we need to minimize the maximum score, and the maimum score is nothing but the the difference between two extremes of the arrays, and by these three choices we tried to reduce this maximum difference.\n\nNow to find the required max and min values, we can also do this in linear-pass instead of sorting, but I\'ll leave that as an exercise for you.\n\nDo Upvote!\n\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n Arrays.sort(nums);\n int min = nums[nums.length-3] - nums[0];\n min = Math.min(nums[nums.length-1] - nums[2], min);\n min = Math.min(nums[nums.length-2] - nums[1], min);\n \n return min;\n \n }\n}\n```
2
0
['Java']
0
minimum-score-by-changing-two-elements
C++ 2 line Easy Code.
c-2-line-easy-code-by-sagargupta1610-62ok
Complexity\n- Time complexity: O(n*log(n))\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \
Sagargupta1610
NORMAL
2023-02-18T16:18:35.224636+00:00
2023-02-18T16:18:35.224678+00:00
35
false
# Complexity\n- Time complexity: $$O(n*log(n))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int n=nums.size();\n return min({nums[n-1]-nums[2],nums[n-3]-nums[0],nums[n-2]-nums[1]});\n }\n};\n```
2
0
['C++']
0
minimum-score-by-changing-two-elements
[Java] Best choice from three cases
java-best-choice-from-three-cases-by-0x4-w4us
Intuition\n Describe your first thoughts on how to solve this problem. \nJust sort the array and use greedy method.\n\n# Approach\n Describe your approach to so
0x4c0de
NORMAL
2023-02-18T16:00:30.744852+00:00
2023-02-18T16:12:29.908562+00:00
364
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nJust sort the array and use greedy method.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**We can alwasy make lower score to 0 by keeping same number, so we can focus on high score.**\n\nTo get minimum high score, we should keep minimum of |hightest - lowerest| value.\nWe have three cases:\n1. Change `nums[0]` and `nums[1]` to `nums[2]`\n2. Change `nums[0]` to `nums[1]` and `nums[n - 1]` to `nums[n - 2]`\n3. Change `nums[n - 2]` and `nums[n - 1]` to `nums[n - 3]`\n\n# Complexity\n- Time complexity: $$O(N*logN)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n final int n = nums.length;\n Arrays.sort(nums);\n // high score\n int high = Integer.MAX_VALUE;\n // left and right\n high = Math.min(high, nums[n - 2] - nums[1]);\n\n // right and right\n high = Math.min(high, nums[n - 3] - nums[0]);\n\n // left and left\n high = Math.min(high, nums[n - 1] - nums[2]);\n\n return high;\n }\n}\n\n```
2
0
['Greedy', 'Java']
0
minimum-score-by-changing-two-elements
5 Lines Code || DP || Easy C++ || Beats 100% ✅✅
5-lines-code-dp-easy-c-beats-100-by-deep-q0iu
\n# Approach\n Describe your approach to solving the problem. \nWe have to choose two numbers from minimum or maximum but which two elements will we choose.....
Deepak_5910
NORMAL
2023-08-06T16:19:09.846096+00:00
2023-08-06T16:19:09.846116+00:00
76
false
\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe have to **choose two numbers** from **minimum or maximum** but which two elements will we **choose**.........\uD83E\uDD14\uD83E\uDD14\uD83E\uDD14\uD83E\uDD14\nHere I used **dp concept** to select two elements so as to **minimize the score sum**.\n\n# Complexity\n- Time complexity:O(N * Log(N))\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int solve(vector<int> arr,int i,int j,int k)\n {\n if(k>=2) return arr[j]-arr[i];\n return min(solve(arr,i+1,j,k+1),solve(arr,i,j-1,k+1));\n }\n int minimizeSum(vector<int>& arr) {\n sort(arr.begin(),arr.end());\n if(arr.size()<=3) return 0;\n return solve(arr,0,arr.size()-1,0);\n }\n};\n```\n![upvote.jpg](https://assets.leetcode.com/users/images/897fffe7-61e0-4168-b721-02355350e7cc_1691338716.6880965.jpeg)\n
1
0
['Array', 'Dynamic Programming', 'Greedy', 'C++']
0
minimum-score-by-changing-two-elements
[Golang] Simple solution
golang-simple-solution-by-user0440h-sqfe
Complexity\n- Time complexity: O(N Log N)\n- Space complexity: O(1)\n\n# Code\n\nfunc minimizeSum(nums []int) int {\n sort.Ints(nums)\n n := len(nums)\n // S
user0440H
NORMAL
2023-07-02T00:19:04.373438+00:00
2023-07-02T00:19:04.373457+00:00
12
false
# Complexity\n- Time complexity: O(N Log N)\n- Space complexity: O(1)\n\n# Code\n```\nfunc minimizeSum(nums []int) int {\n sort.Ints(nums)\n n := len(nums)\n // Since we can only make at most 2 modifications\n // We either change the first two elements, last two elements\n // or the first and last element.\n res := nums[n-3] - nums[0]\n if nums[n-2] - nums[1] < res {\n res = nums[n-2] - nums[1]\n }\n if nums[n-1] - nums[2] < res {\n res = nums[n-1] - nums[2]\n }\n return res\n}\n\nfunc abs(a int) int {\n if a < 0 {\n return -a\n }\n return a\n}\n```
1
0
['Sorting', 'Go']
0
minimum-score-by-changing-two-elements
JAVA very easy solution
java-very-easy-solution-by-21arka2002-ygc2
Approach\nSort the array in ascending order\nThree Cases can occur-\n1. Remove first two elements\n2. Remove last two elements\n3. Remove first and the last ele
21Arka2002
NORMAL
2023-04-03T04:52:51.378084+00:00
2023-04-03T04:52:51.378115+00:00
75
false
### Approach\nSort the array in ascending order\nThree Cases can occur-\n1. Remove first two elements\n2. Remove last two elements\n3. Remove first and the last element\n\n\n\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n Arrays.sort(nums);\n int d1=(nums[nums.length-1]-nums[2]);\n int d2=(nums[nums.length-1-2]-nums[0]);\n int d3=(nums[nums.length-1-1]-nums[1]);\n return (int)(Math.min(d1,Math.min(d2,d3)));\n }\n}\n```
1
0
['Array', 'Greedy', 'Sorting', 'Java']
0
minimum-score-by-changing-two-elements
Sorting approach | Java solution | Clean Code
sorting-approach-java-solution-clean-cod-02bc
Intuition\nIf we make two elements equal then value of low will be 0. Hence we can utilize both the two operations in minimizing the value of high\n\n# Approach
vrutik2809
NORMAL
2023-02-21T18:22:39.863450+00:00
2023-02-21T18:22:39.863493+00:00
32
false
# Intuition\nIf we make two elements equal then value of `low` will be `0`. Hence we can utilize both the two operations in minimizing the value of `high`\n\n# Approach\n- Sort the array in acending order\n- We can minimize the value of `high` using any of the following three operations:\n 1. If we make `nums[0] = nums[n - 1]` & `nums[1] = nums[n - 1]` then `ans` will be `nums[n - 1] - nums[2]`\n 2. If we make `nums[n - 1] = nums[0]` & `nums[n - 2] = nums[0]` then `ans` will be `nums[n - 3] - nums[0]`\n 3. If we make `nums[0] = nums[1]` & `nums[n - 1] = nums[n - 2]` then `ans` will be `nums[n - 2] - nums[1]`\n\n- Take **minimum** of above three answers\n\n# Complexity\n- Time complexity: $O(n * logn)$\n\n- Space complexity: $O(1)$\n\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n Arrays.sort(nums);\n int n = nums.length;\n int ans = Math.min(nums[n - 1] - nums[2],nums[n - 3] - nums[0]);\n ans = Math.min(ans,nums[n - 2] - nums[1]);\n return ans;\n }\n}\n```\n\n# Upvote if you like it \uD83D\uDC4D\uD83D\uDC4D
1
0
['Sorting', 'Java']
0
minimum-score-by-changing-two-elements
Sort + Greedy | C++
sort-greedy-c-by-tusharbhart-quuy
\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n return min
TusharBhart
NORMAL
2023-02-20T16:29:30.496096+00:00
2023-02-20T16:29:30.496248+00:00
39
false
```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n int n = nums.size();\n return min({nums[n - 3] - nums[0], nums[n - 1] - nums[2], nums[n - 2] - nums[1]});\n }\n};\n```
1
0
['Greedy', 'Sorting', 'C++']
0
minimum-score-by-changing-two-elements
C++ || Easy approach
c-easy-approach-by-mrigank_2003-ps2w
Here is my c++ code for this problem.\n\n# Complexity\n- Time complexity:O(nlogn)\n\n- Space complexity:O(n)\n\n# Code\n\nclass Solution {\npublic:\n int min
mrigank_2003
NORMAL
2023-02-20T09:08:36.432907+00:00
2023-02-20T09:08:36.432955+00:00
41
false
Here is my c++ code for this problem.\n\n# Complexity\n- Time complexity:$$O(nlogn)$$\n\n- Space complexity:$$O(n)$$\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(), nums.end());\n // if(nums.size()==3){return 0;}\n // vector<int>v=nums;\n // int mini=*min_element(nums.begin(), nums.end()), k=2;\n // while(k--){\n // int maxi=*max_element(nums.begin(), nums.end());\n // for(int i=0; i<nums.size(); i++){\n // if(nums[i]==maxi){nums[i]=mini;}\n // }\n // }\n // int n1=*min_element(nums.begin(), nums.end()), n2=*max_element(nums.begin(), nums.end());\n // int k1=2, maxi1=*max_element(v.begin(), v.end());\n // cout<<maxi1<<endl;\n // while(k1--){\n // int mini1=*min_element(v.begin(), v.end());\n // for(int i=0; i<v.size(); i++){\n // if(v[i]==mini1){v[i]=maxi1;}\n // }\n // }\n // int nn1=*min_element(v.begin(), v.end()), nn2=*max_element(v.begin(), v.end());\n // cout<<nn2-nn1<<" "<<n2-n1<<endl;\n return min({nums[nums.size()-1]-nums[0], nums[nums.size()-2]-nums[1], nums[nums.size()-1]-nums[2], nums[nums.size()-3]-nums[0]});\n }\n};\n```
1
0
['C++']
0
minimum-score-by-changing-two-elements
Explanation and C++ Solution
explanation-and-c-solution-by-shubham_mi-mkb9
Intuition\n Describe your first thoughts on how to solve this problem. \nIf we make two numbers equal, we can make the low score equal to 0. So only thing left
Shubham_Mi
NORMAL
2023-02-19T07:15:33.841704+00:00
2023-02-19T07:15:33.841760+00:00
164
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIf we make two numbers equal, we can make the __low__ score equal to `0`. So only thing left is to find minimum __high__ score.\nThe __high__ score will depend on the minimum and the maximum value in the array. So, we should either decrease the maximum values or increase the minimum values. There are __three__ posibilitites:\n- We decrease the top two values to third highest value.\n- We increase the bottom two value to third smallest value.\n- We increase the bottom value to second smallest value and decrease the top value to second highest value.\n\nIn all the above cases, __low__ will be `0`.\n\n# Complexity\n- Time complexity: O(1)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int n = nums.size();\n if (n == 3) return 0;\n sort(nums.begin(), nums.end());\n return min(nums[n - 1] - nums[2], min(nums[n - 3] - nums[0], nums[n - 2] - nums[1]));\n }\n};\n```
1
0
['Math', 'Sorting', 'C++']
0
minimum-score-by-changing-two-elements
C++ || Easy Explanation with comments ||
c-easy-explanation-with-comments-by-khwa-jqw8
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nTo Minimine our Ans We need to do two things :\n1. Maximize the maximum d
Khwaja_Abdul_Samad
NORMAL
2023-02-18T18:40:37.558510+00:00
2023-02-18T18:40:37.558555+00:00
74
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nTo Minimine our Ans We need to do two things :\n1. Maximize the maximum difference of two numbers. \n2. Minimize the minimum difference of two numbers.\n\nNow to minimize the difference of two number we can always minimze it to zero by changing one number to another number .\nTo maximize the difference of two number we have three options :\nA. Change last two number to first number .\nB. Change first two number to last number .\nC. Change first number to second number and last number to second last number .\n\n\n# Complexity\n- Time complexity: O(Log(n))\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n \n int n = nums.size();\n sort(nums.begin() , nums.end());\n \n //Option A\n int op1 = nums[n-3] - nums[0];\n //Option B\n int op2 = nums[n-1] - nums[2];\n //Option C\n int op3 = nums[n-2] - nums[1];\n \n \n return min(op1 , min(op2, op3));\n \n }\n};\n```
1
0
['Sorting', 'C++']
0
minimum-score-by-changing-two-elements
C++||Most Easy Solution with Explanation
cmost-easy-solution-with-explanation-by-ggik3
\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n //increase th
Arko-816
NORMAL
2023-02-18T18:15:51.339792+00:00
2023-02-18T18:15:51.339843+00:00
35
false
```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int n=nums.size();\n sort(nums.begin(),nums.end());\n //increase the smallest two numbers\n int a=nums[n-1]-nums[2];\n //decrease the two largest nos\n int b=nums[n-3]-nums[0];\n //increase the smallest no and decrease the largest no\n int c=nums[n-2]-nums[1];\n return min({a,b,c});\n }\n};\n```
1
0
[]
0
minimum-score-by-changing-two-elements
Python Solution || 2 lines || Easy to understand
python-solution-2-lines-easy-to-understa-er78
\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n n,_ = len(nums),nums.sort()\n return min([nums[n-1]-nums[0],nums[n-3]-nums
mohitsatija
NORMAL
2023-02-18T18:03:41.756337+00:00
2023-02-18T18:03:41.756368+00:00
50
false
```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n n,_ = len(nums),nums.sort()\n return min([nums[n-1]-nums[0],nums[n-3]-nums[0],nums[n-1]-nums[2],nums[n-2]-nums[1]])\n```
1
0
['Array', 'Math', 'Greedy', 'Sorting', 'Python', 'Python3']
0
minimum-score-by-changing-two-elements
Java sorting detailed solution
java-sorting-detailed-solution-by-callme-nhm5
class Solution {\n public int minimizeSum(int[] nums) {\n int n=nums.length;\n Arrays.sort(nums);\n //Remove first and last elem\n
callmecomder
NORMAL
2023-02-18T17:50:28.125201+00:00
2023-02-18T17:50:28.125242+00:00
22
false
# class Solution {\n public int minimizeSum(int[] nums) {\n int n=nums.length;\n Arrays.sort(nums);\n //Remove first and last elem\n int a=nums[n-2]-nums[1];\n //Remove first two elements\n int b=nums[n-1]-nums[2];\n //Remove last two elements\n int c=nums[n-3]-nums[0];\n //return minimum of all\n return Math.min(a,Math.min(b,c));\n }\n}
1
0
['Sorting', 'Java']
0
minimum-score-by-changing-two-elements
only 2 line answer easy to understand both line explain good
only-2-line-answer-easy-to-understand-bo-9p3d
Approach\n Describe your approach to solving the problem. \nwe have 3 case for 2 element remove\n1. 2 minimum\n2. 2 maximum\n3. 1 minimum and 1 maximum\n\nfor a
mandliyarajendra11
NORMAL
2023-02-18T17:46:47.426726+00:00
2023-02-18T17:51:05.190681+00:00
60
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nwe have 3 case for 2 element remove\n1. 2 minimum\n2. 2 maximum\n3. 1 minimum and 1 maximum\n\nfor all cases low always 0 \nand high is (as a que maximum-minimum) after remove \n2 element \n\n1. ```nums[nums.size()-1]-nums[2]```\n2. ```nums[nums.size()-3]-nums[0]```\n3. ```nums[nums.size()-2]-nums[1]```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n O(nlogn)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --> \n O(1)\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n \n sort(nums.begin(),nums.end());\n \n return min({nums[nums.size()-2]-nums[1],nums[nums.size()-1]-nums[2],nums[nums.size()-3]-nums[0]});\n \n }\n};\n```
1
0
['C++']
0
minimum-score-by-changing-two-elements
C++ simple 4 line Solution
c-simple-4-line-solution-by-technoreck-l1ii
Code\n\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n if(nums.size()==3){\n return 0;\n }\n int n = nums
technoreck
NORMAL
2023-02-18T16:52:14.679938+00:00
2023-02-18T16:52:14.679972+00:00
46
false
# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n if(nums.size()==3){\n return 0;\n }\n int n = nums.size();\n sort(nums.begin(),nums.end());\n int ans1 = nums[n-3] - nums[0];\n int ans2 = nums[n-2] - nums[1];\n int ans3 = nums[n-1] - nums[2];\n return min(min(ans1,ans2),min(ans2,ans3));\n }\n};\n```
1
0
['C++']
0
minimum-score-by-changing-two-elements
100% ACCEPTANCE..VERY EASY APPROACH ...REDUCING THE MAXIMUM DIFFERENCE IN INTERVAL
100-acceptancevery-easy-approach-reducin-i94p
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
PagalavanPagal66
NORMAL
2023-02-18T16:36:46.097079+00:00
2023-02-18T16:36:46.097115+00:00
36
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& num) {\n if(num.size()==3){\n return 0;\n }\n sort(num.begin(),num.end());\n int n=num.size();\n int mini=min(num[n-1]-num[2],num[n-3]-num[0]);\n return min(mini,num[n-2]-num[1]);\n }\n};\n```
1
0
['Greedy', 'Sorting', 'C++']
0
minimum-score-by-changing-two-elements
Easy Java Solution
easy-java-solution-by-1asthakhushi1-enf2
\n# Code\n\nclass Solution {\n public int minimizeSum(int[] nums) {\n Arrays.sort(nums);\n int ref=nums[2];\n int high=nums[nums.length-
1asthakhushi1
NORMAL
2023-02-18T16:04:52.170090+00:00
2024-02-27T06:26:00.610854+00:00
146
false
\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n Arrays.sort(nums);\n int ref=nums[2];\n int high=nums[nums.length-1]-ref;\n int ref2=nums[nums.length-3];\n int high2=ref2-nums[0];\n \n int high3=nums[nums.length-2]-nums[1];\n return Math.min(Math.min(high,high2),high3);\n }\n}\n```
1
0
['Array', 'Math', 'Java']
0
minimum-score-by-changing-two-elements
Easy Approach || C++✅
easy-approach-c-by-101rror-fjwb
Code\n\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums)\n {\n int n = nums.size();\n \n sort(nums.begin(), nums.end())
101rror
NORMAL
2023-02-18T16:04:07.238431+00:00
2023-02-18T16:04:07.238493+00:00
26
false
# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums)\n {\n int n = nums.size();\n \n sort(nums.begin(), nums.end());\n \n int ans = min({nums[n - 1] - nums[0], nums[n - 1] - nums[2], nums[n - 3] - nums[0], nums[n - 2] - nums[1]});\n \n return ans;\n }\n};\n```
1
0
['Sorting', 'C++']
0
minimum-score-by-changing-two-elements
Think about corner elements after sorting
think-about-corner-elements-after-sortin-nc3e
\n\n# Code\n\nclass Solution {\npublic:\n int minimizeSum(vector<int>& a) {\n sort(a.begin(),a.end());\n return min({\n a.back() - a[
__Abcd__
NORMAL
2023-02-18T16:02:16.100832+00:00
2023-02-18T16:02:16.100866+00:00
55
false
\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& a) {\n sort(a.begin(),a.end());\n return min({\n a.back() - a[2],\n a[size(a)-2] - a[1],\n a[size(a)-3] - a[0]\n });\n }\n};\n```
1
0
['C++']
0
minimum-score-by-changing-two-elements
3 liner | Easy C++ code 🔥🔥🔥
3-liner-easy-c-code-by-iritikkumar7-l8gp
Just check three cases\n\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end
iritikkumar7
NORMAL
2023-02-18T16:01:54.301011+00:00
2023-02-18T16:02:29.673023+00:00
117
false
Just check three cases\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n return min({nums[n-1]-nums[2], nums[n-3]-nums[0], nums[n-2]-nums[1]});\n }\n};\n```
1
0
['C']
1
minimum-score-by-changing-two-elements
C++ || 3 Choices Sort
c-3-choices-sort-by-up1512001-ytuk
\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n if(nums.size()<=3) return 0;\n \n vector<int> first,middle;\n
up1512001
NORMAL
2023-02-18T16:01:30.596515+00:00
2023-02-18T16:01:30.596566+00:00
165
false
```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n if(nums.size()<=3) return 0;\n \n vector<int> first,middle;\n sort(nums.begin(),nums.end());\n first = nums;\n middle = nums;\n \n nums[0] = nums[2];\n nums[1] = nums[2];\n int ans1 = nums.back()-nums[0];\n \n first[first.size()-1] = first[0];\n first[first.size()-2] = first[0];\n sort(first.begin(),first.end());\n int ans2 = first.back()-first[0];\n \n \n middle[middle.size()-1] = middle[1];\n middle[0] = middle[1];\n sort(middle.begin(),middle.end());\n int ans3 = middle.back()-middle[0];\n \n \n return min(ans1,min(ans2,ans3));\n \n }\n};\n```
1
0
['C', 'Sorting', 'C++']
0
minimum-score-by-changing-two-elements
Three Cases to Calculation
three-cases-to-calculation-by-linda2024-wcbv
IntuitionApproachComplexity Time complexity: Space complexity: Code
linda2024
NORMAL
2025-04-09T17:34:19.940082+00:00
2025-04-09T17:34:19.940082+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```csharp [] public class Solution { public int MinimizeSum(int[] nums) { int len = nums.Length; if(len < 4) return 0; Array.Sort(nums); // 3 cases: // Relace two lower items int res = nums[len-1] - nums[2]; // Replace two higher items: res = Math.Min(res, nums[len-3]-nums[0]); // Replace lowest and highest items: res = Math.Min(res, nums[len-2] - nums[1]); return res; } } ```
0
0
['C#']
0
minimum-score-by-changing-two-elements
Easy to understand, straightforward with explanation
easy-to-understand-straightforward-with-fon53
IntuitionAfter reading the question it was clear that ordering of elements doesn't matter and we are dealing max/min diff so sorting seemed an option, also sinc
shubham1697
NORMAL
2025-02-25T05:49:09.836452+00:00
2025-02-25T05:49:09.836452+00:00
5
false
# Intuition After reading the question it was clear that ordering of elements doesn't matter and we are dealing max/min diff so sorting seemed an option, also since we are allowed to change at most two elements so low score will always be zero as difference of equal elements is zero so we need to minimize max score only # Approach Sort the arrays and consider min difference of removing all the 3 combinations of elements # Complexity - Time complexity: O(nlogn) - Space complexity: O(1) # Code ```python3 [] class Solution: def minimizeSum(self, nums: List[int]) -> int: nums.sort() if len(nums)<=3: return 0 else: n=len(nums)-1 return min(nums[n]-nums[2],nums[n-1]-nums[1],nums[n-2]-nums[0]) ```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
Simple Intuitive Approach
simple-intuitive-approach-by-jihyuk3885-ovss
IntuitionSince low scores always become 0 after changing, it is important to make the high score small.ApproachSince the high score is the gap between the large
jihyuk3885
NORMAL
2025-02-03T11:34:01.749683+00:00
2025-02-03T11:34:01.749683+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Since low scores always become 0 after changing, it is important to make the high score small. # Approach <!-- Describe your approach to solving the problem. --> Since the high score is the gap between the largest and smallest values, to reduce this gap, you need to make the largest value smaller or the smallest value larger. # Complexity - Time complexity: $$O(NlogN)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: $$O(N)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int minimizeSum(vector<int>& nums) { sort(nums.begin(), nums.end()); int n = nums.size(); // case 1. remove the two biggests. int ans1 = nums[n-3] - nums[0]; // case 2. remove the two lowests. int ans2 = nums[n-1] - nums[2]; // case 3. remove the biggest and the lowest. int ans3 = nums[n-2] - nums[1]; return min({ans1, ans2, ans3}); } }; ```
0
0
['C++']
0
minimum-score-by-changing-two-elements
CPP | Sorting + Greedy
cpp-sorting-greedy-by-kena7-m2be
Code
kenA7
NORMAL
2025-02-03T04:29:27.012959+00:00
2025-02-03T04:29:27.012959+00:00
2
false
# Code ```cpp [] class Solution { public: int minimizeSum(vector<int>& nums) { sort(nums.begin(),nums.end()); int n=nums.size(); int res=nums[n-1]-nums[2]; res=min(res, nums[n-3]-nums[0]); res=min(res,nums[n-2]-nums[1]); return res; } }; ```
0
0
['C++']
0
minimum-score-by-changing-two-elements
python
python-by-vishwanath20023-e65t
Code
vishwanath20023
NORMAL
2025-01-27T07:46:33.361995+00:00
2025-01-27T07:46:33.361995+00:00
3
false
# Code ```python3 [] class Solution: def minimizeSum(self, nums: List[int]) -> int: nums.sort() return min((nums[-1]-nums[2]),(nums[-3]-nums[0]),(nums[-2]-nums[1])) ```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
2567. Minimum Score by Changing Two Elements
2567-minimum-score-by-changing-two-eleme-o3ra
IntuitionApproachComplexity Time complexity: Space complexity: Code
G8xd0QPqTy
NORMAL
2025-01-19T03:24:29.234788+00:00
2025-01-19T03:24:29.234788+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```python3 [] class Solution: def minimizeSum(self, nums: List[int]) -> int: nums.sort() # Option 1: Change the first two elements option1 = nums[-1] - nums[2] # Option 2: Change the last two elements option2 = nums[-3] - nums[0] # Option 3: Change the first and last elements option3 = nums[-2] - nums[1] return min(option1, option2, option3) ```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
Math | Simple solution with 100% beaten
math-simple-solution-with-100-beaten-by-jjif5
IntuitionTo minimize the score after modifying two elements, we must consider the difference between the largest and smallest values, as well as their "neighbor
Takaaki_Morofushi
NORMAL
2025-01-14T11:05:05.056195+00:00
2025-01-14T11:05:05.056195+00:00
6
false
# Intuition To minimize the score after modifying two elements, we must consider the difference between the largest and smallest values, as well as their "neighbors." The strategy involves identifying possible modifications to the smallest and largest values. By removing two elements, we can minimize the score by either: - Removing the two smallest elements. - Removing the two largest elements. - Removing one smallest and one largest element. # Approach Identify Extreme Values: We first need to find the three smallest and three largest numbers from the array. This will allow us to consider the best candidates for modification without sorting the entire array. # Complexity - Time complexity: O(n) - Space complexity: O(1) # Code ```cpp [] class Solution { public: int minimizeSum(vector<int>& nums) { if (nums.size() == 3) return 0; vector<int> smallest(3, INT_MAX), largest(3, INT_MIN); for (int num : nums) { if (num < smallest[0]) { smallest[2] = smallest[1]; smallest[1] = smallest[0]; smallest[0] = num; } else if (num < smallest[1]) { smallest[2] = smallest[1]; smallest[1] = num; } else if (num < smallest[2]) { smallest[2] = num; } if (num > largest[0]) { largest[2] = largest[1]; largest[1] = largest[0]; largest[0] = num; } else if (num > largest[1]) { largest[2] = largest[1]; largest[1] = num; } else if (num > largest[2]) { largest[2] = num; } } int option1 = largest[0] - smallest[2]; // Remove the two smallest elements int option2 = largest[2] - smallest[0]; // Remove the two largest elements int option3 = largest[1] - smallest[1]; // Remove the smallest and the largest element return min({option1, option2, option3}); } }; ```
0
0
['C++']
0
minimum-score-by-changing-two-elements
Chop chopper
chop-chopper-by-tonitannoury01-vpwq
IntuitionApproachComplexity Time complexity: O(nlog(n)) Space complexity: O(1) Code
tonitannoury01
NORMAL
2025-01-11T17:51:36.728460+00:00
2025-01-11T17:51:36.728460+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(nlog(n)) - Space complexity: O(1) # Code ```javascript [] /** * @param {number[]} nums * @return {number} */ var minimizeSum = function (nums) { if (nums.length <= 3) { return 0; } nums.sort((a, b) => a - b); return Math.min( nums[nums.length - 1] - nums[2], nums[nums.length - 3] - nums[0], nums[nums.length - 2] - nums[1] ); }; ```
0
0
['JavaScript']
0
minimum-score-by-changing-two-elements
C++ Greedy solution
c-greedy-solution-by-oleksam-xdjp
Please, upvote if you like it. Thanks :-)ApproachUse a greedy approach.Complexity Time complexity: O(n log(n)) Space complexity: O(1) Code
oleksam
NORMAL
2025-01-09T11:54:24.880256+00:00
2025-01-09T11:55:14.672011+00:00
4
false
Please, upvote if you like it. Thanks :-) # Approach Use a greedy approach. # Complexity - Time complexity: O(n log(n)) - Space complexity: O(1) # Code ```cpp [] int minimizeSum(vector<int>& nums) { int n = nums.size(); sort(begin(nums), end(nums)); return min( { nums[n - 2] - nums[1], nums[n - 1] - nums[2], nums[n - 3] - nums[0] } ); } ```
0
0
['Array', 'Greedy', 'Sorting', 'C++']
0
minimum-score-by-changing-two-elements
// Changing the minimum or maximum values will only minimize the score is the key to solving it
changing-the-minimum-or-maximum-values-w-kym6
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
2manas1
NORMAL
2024-11-24T14:19:57.002044+00:00
2024-11-24T14:19:57.002075+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution\n{\n public int minimizeSum(int[] nums)\n {\n Arrays.sort(nums);\n return Math.min(Math.min(nums[nums.length-1]-nums[2],nums[nums.length-3]-nums[0]),nums[nums.length-2] - nums[1]);\n }\n}\n```
0
0
['Math', 'Java']
0
minimum-score-by-changing-two-elements
Uhh... find k first min elements and k first max elements
uhh-find-k-first-min-elements-and-k-firs-j1vw
Intuition\n Describe your first thoughts on how to solve this problem. \nAnother tricky problem when reading requirement, but turns into a simple problem if you
minhtud04
NORMAL
2024-11-20T19:09:23.308869+00:00
2024-11-20T19:09:23.308901+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAnother tricky problem when reading requirement, but turns into a simple problem if you translate + rephrase it properly :)\n\nHere I need to find min-range and max-range after change k numbers. Notice that I could change to any number -> I could always get min-range == 0.\n\nNow I need to minimize the max-range. Here, if I generalize to k numbers --> I need to find the min pair range between the first k min number and first k max number (min[0] and max[k] -> min[k] and max[0])\n\nThe most optimized approach to find first k min number and first k max number is properly using a heap -> nlogk. However, a sorting solution of nlogn is also okay for me.\n\nIn this problem, since n == 2 only -> We could achieve a 0(N) without using extra space. (In another problem of leetcode already had find 2 firt min/max)\n\n\n\n# Complexity\n- Time complexity:n\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n #3 combination\n nums.sort()\n\n firstRev = nums[-1] - nums[2]\n lastRev = nums[-3] - nums[0]\n bothRev = nums[-2] - nums[1]\n\n return min(firstRev, lastRev, bothRev)\n```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
100 % faster
100-faster-by-rohitgupta_2254-hdgw
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach \nSort the Array: \nSorting helps easily find the smallest and largest ele
rohitgupta_2254
NORMAL
2024-11-15T08:20:00.745318+00:00
2024-11-15T08:20:00.745355+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach \nSort the Array: \nSorting helps easily find the smallest and largest elements, and it allows us to calculate the smallest differences between consecutive elements.\n\nPossible Changes:\nAfter sorting, consider adjusting the two smallest or two largest elements to reduce the maximum range.\nFor example, in the sorted array, try setting the smallest two values close to the next larger values or the largest two values close to the next smaller values.\n\nCalculate Scores:\nFor each possible adjustment, calculate the new high and low scores.\nTrack the minimum score across these adjustments.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int minimizeSum(int[] nums) {\n int n = nums.length;\n // Sort the array\n Arrays.sort(nums);\n \n // Initial potential results by making changes to the smallest/largest elements\n int option1 = nums[n - 1] - nums[2]; // Replace first two elements with the third element\n int option2 = nums[n - 3] - nums[0]; // Replace last two elements with the third-last element\n int option3 = nums[n - 2] - nums[1]; // Replace first and last elements with second and second-last elements\n \n // Minimum of the potential scores after changes\n return Math.min(option1, Math.min(option2, option3));\n }\n}\n```
0
0
['Java']
0
minimum-score-by-changing-two-elements
Minimum Score by Changing Two Elements
minimum-score-by-changing-two-elements-b-haj6
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Naeem_ABD
NORMAL
2024-11-13T05:50:03.206824+00:00
2024-11-13T05:50:03.206848+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n if(nums.size()==3){\n return 0;\n }\n int n = nums.size();\n sort(nums.begin(),nums.end());\n int ans1 = nums[n-3] - nums[0];\n int ans2 = nums[n-2] - nums[1];\n int ans3 = nums[n-1] - nums[2];\n return min(min(ans1,ans2),min(ans2,ans3));\n }\n};\n```
0
0
['C++']
0
minimum-score-by-changing-two-elements
python - O(n)/O(1) - No Sorting/No heap
python-ono1-no-sortingno-heap-by-randomq-ly9a
Intuition\n\nThere are only 3 possibilities:\n- change the two smallest values: score becomes largest minus third smallest\n- change the two largest values: sco
randomQuant
NORMAL
2024-11-07T15:23:09.946631+00:00
2024-11-07T15:23:09.946667+00:00
0
false
# Intuition\n\nThere are only 3 possibilities:\n- change the two smallest values: score becomes largest minus third smallest\n- change the two largest values: score becomes third largest minus smallest\n- change the largest and smallest values: score becomes second largest minus second smallest\n\nWhen we change a variable, we change it to some other value that remains in the array (we do not care about this value).\n\nTherefore we only care about the 3 smallest and 3 largest values and we can get them in $O(n)$ and $O(1)$.\n\n# Approach\n\nWe go though the array and keep track of the 3 smallest and 3 largest values. After this we return the minimum combination.\n\n# Complexity\n- Time complexity:\n$O(n)$ - We go through the array once.\n\n- Space complexity:\n$O(1)$ - We only use constant extra space for the 6 variables of interest.\n\n# Code\n```python3 []\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n \n min1, min2, min3, max1, max2, max3 = float(\'inf\'), float(\'inf\'), float(\'inf\'), 0, 0, 0\n for i, num in enumerate(nums):\n if num <= min1:\n min3 = min2\n min2 = min1\n min1 = num\n elif num <= min2:\n min3 = min2\n min2 = num\n elif num < min3:\n min3 = num\n if num >= max1:\n max3 = max2\n max2 = max1\n max1 = num\n elif num >= max2:\n max3 = max2\n max2 = num\n elif num > max3:\n max3 = num\n\n return min(max2 - min2, max1 - min3, max3 - min1)\n```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
Simple Java Solution
simple-java-solution-by-sakshikishore-l72r
Code\njava []\nclass Solution {\n public int minimizeSum(int[] nums) {\n Arrays.sort(nums);\n if(nums.length==3)\n {\n return
sakshikishore
NORMAL
2024-10-23T13:12:27.717306+00:00
2024-10-23T13:12:27.717337+00:00
0
false
# Code\n```java []\nclass Solution {\n public int minimizeSum(int[] nums) {\n Arrays.sort(nums);\n if(nums.length==3)\n {\n return 0;\n }\n int min=nums[nums.length-1]-nums[2];\n if(nums[nums.length-2]-nums[1]<min)\n {\n min=nums[nums.length-2]-nums[1];\n }\n if(nums[nums.length-3]-nums[0]<min)\n {\n min=nums[nums.length-3]-nums[0];\n }\n\n return min;\n }\n}\n```
0
0
['Java']
0
minimum-score-by-changing-two-elements
O(n) heapq Solution | 235ms | Beats 99%
on-heapq-solution-235ms-beats-99-by-padt-va0y
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(1)\n Add your space complexity here, e.g. O(n) \n\n# Co
padth
NORMAL
2024-10-02T01:25:21.343339+00:00
2024-10-02T01:25:21.343364+00:00
3
false
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n low = heapq.nsmallest(3, nums)\n high = heapq.nlargest(3, nums)\n\n a = high[0] - low[2] # Remove the first 2\n b = high[2] - low[0] # Remove the last 2\n c = high[1] - low[1] # Remove first and last\n\n return min([a, b, c])\n```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
for loop python code
for-loop-python-code-by-rakshitha0912-83uq
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
rakshitha0912
NORMAL
2024-09-17T07:22:12.835674+00:00
2024-09-17T07:22:12.835707+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python3 []\nclass Solution:\n def minimizeSum(self, nums: list[int]) -> int:\n s_nums = sorted(nums)\n k = 2\n return min(\n s_nums[i] - s_nums[j]\n for i, j in zip(range(-1, -k - 2, -1), range(k, -1, -1))\n )\n\n```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
c++
c-by-indian_2000error404-0xkn
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
INDIAN_2000ERROR404
NORMAL
2024-09-10T22:20:35.380817+00:00
2024-09-10T22:20:35.380835+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n \n int n=nums.size();\n if(n==3){\n return 0;\n } \n\n sort(nums.begin(),nums.end());\n\n return min(nums[n-2]-nums[1],min(nums[n-3]-nums[0],nums[n-1]-nums[2]));\n\n\n }\n};\n```
0
0
['C++']
0
minimum-score-by-changing-two-elements
c++ easy solution
c-easy-solution-by-baku12-3eiy
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
baku12
NORMAL
2024-09-10T10:36:34.001282+00:00
2024-09-10T10:36:34.001313+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n\n\nsort(nums.begin(),nums.end());\n\nif(nums.size()<=2)\nreturn 0;\n\nint n=nums.size();\nint x=nums[2];\n\n int a=nums[n-1]-x;\n int b=nums[n-3]-nums[0];\n int c=nums[n-2]-nums[1];\n\n return min(a,min(b,c));\n\n\n\n\n\n\n\n\n\n\n\n \n \n }\n};\n```
0
0
['C++']
0
minimum-score-by-changing-two-elements
O(n) time, O(1) space, no sorting required
on-time-o1-space-no-sorting-required-by-ha1o8
Approach\nNo need to sort the array instead do the following:\n\nFind 1st 3 minimum values (low1<=low2<=low3) and 1st 3 maximum values (high1>=high2>=high3)\n\n
kakshayiitk
NORMAL
2024-09-02T14:24:24.774384+00:00
2024-09-02T14:24:24.774429+00:00
4
false
# Approach\nNo need to sort the array instead do the following:\n\nFind 1st 3 minimum values (low1<=low2<=low3) and 1st 3 maximum values (high1>=high2>=high3)\n\nAnswer is minimum difference between the pairs (high1,low3), (high2,low2), (high3,low1)\n# Complexity\n- Time complexity:\nO(n) - finding min and max values of array\n\n- Space complexity:\nO(1)\n\n# Code\n```python3 []\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n low1 = min(nums)\n nums.remove(low1)\n\n low2 = min(nums)\n nums.remove(low2)\n\n low3 = min(nums)\n\n high1 = max(nums)\n\n if len(nums) == 1:\n return 0\n elif len(nums) == 2:\n return min(high1-low3,low3-low2,low2-low1)\n\n nums.remove(high1)\n\n high2 = max(nums)\n nums.remove(high2)\n\n high3 = max(nums)\n\n return min(high1-low3,high2-low2,high3-low1)\n \n```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
scala twoliner
scala-twoliner-by-vititov-laxz
scala []\nobject Solution {\n def minimizeSum(nums: Array[Int]): Int =\n lazy val sorted = nums.sorted\n Iterator(\n sorted(sorted.length-1) - sorte
vititov
NORMAL
2024-09-01T12:39:47.419001+00:00
2024-09-01T12:39:47.419035+00:00
0
false
```scala []\nobject Solution {\n def minimizeSum(nums: Array[Int]): Int =\n lazy val sorted = nums.sorted\n Iterator(\n sorted(sorted.length-1) - sorted(2),\n sorted(sorted.length-2) - sorted(1),\n sorted(sorted.length-3) - sorted(0)\n ).min\n}\n```
0
0
['Greedy', 'Sorting', 'Scala']
0
minimum-score-by-changing-two-elements
Greedy Solution
greedy-solution-by-ni_har15-5wdq
\n\n# Approach\nhum greedy approach laga raha hai jaha pe 3 conditions possible hai .\n1. Starting ke 2 elements equal kar do \n2. Last ke 2 elements equal ka
ni_har15
NORMAL
2024-08-22T17:59:37.149829+00:00
2024-08-22T17:59:37.149864+00:00
4
false
\n\n# Approach\nhum greedy approach laga raha hai jaha pe 3 conditions possible hai .\n1. Starting ke 2 elements equal kar do \n2. Last ke 2 elements equal kar do \n3. First aur last ke 2 elements equal kar do\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:o(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int minimizeSum(int[] nums) {\n\n int n = nums.length ;\n if(n <= 3){\n return 0;\n }\n Arrays.sort(nums);\n int op1 = nums[n-1] - nums[2];\n int op2 = nums[n-3] - nums[0];\n int op3 = nums[n-2] - nums[1];\n return Math.min(op1 , Math.min(op2, op3));\n }\n}\n```
0
0
['Java']
0
minimum-score-by-changing-two-elements
Python - beats 99%, true O(n) runtime, no sorting
python-beats-99-true-on-runtime-no-sorti-d641
Intuition\nSorting is an O(n log n) operation, we can do this in O(n) without sorting\n\n# Approach\nIf we have 3 elements, select 1 element, the other 2 can be
j13622
NORMAL
2024-08-16T03:07:48.555415+00:00
2024-08-16T03:07:48.555435+00:00
1
false
# Intuition\nSorting is an O(n log n) operation, we can do this in O(n) without sorting\n\n# Approach\nIf we have 3 elements, select 1 element, the other 2 can be made into that element, guaranteeing a 0 solution.\n\nIf we have 4 elements, by switching 2 we guarantee that the array contains only 2 unique elements, we choose the 2 unique elements that have the least difference between them.\n\nIf we have > 4 elements, ignore temporarily the low score. Notice that the high score is always the minimum element minus the maximum, if we switch a min off, the new high score is the old max minus the new minimum. Therefore, if we get 2 switches, the potential options for lowest high score are by switching off 2 mins, switching off 2 maxes, or switching off a min and a max. Since we\'re only ever switching off 2 numbers from the top or bottom, we can switch them to any middle number and it will guarantee low score = 0. Just need to keep track of the 3 mins and maxes as we iterate through array in O(n) time\n\n# Complexity\n- Time complexity:\nO(n), to iterate through array once\n\n- Space complexity:\nO(1) extra space\n\n# Code\n```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n if len(nums) == 3:\n return 0\n if len(nums) == 4:\n nums = sorted(nums)\n return min(nums[3] - nums[2], nums[2] - nums[1], nums[1] - nums[0])\n min1, min2, min3 = 1000000001, 1000000001, 1000000001\n max1, max2, max3 = 0, 0, 0\n for i in nums:\n if i < min1:\n min3 = min2\n min2 = min1\n min1 = i\n elif i < min2:\n min3 = min2\n min2 = i\n elif i < min3:\n min3 = i\n if i > max1:\n max3 = max2\n max2 = max1\n max1 = i\n elif i > max2:\n max3 = max2\n max2 = i\n elif i > max3:\n max3 = i\n return min(max2 - min2, max1 - min3, max3 - min1)\n```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
Simple and Easy JAVA Solution , Basic maths
simple-and-easy-java-solution-basic-math-9ejh
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Triyaambak
NORMAL
2024-07-14T15:37:04.378835+00:00
2024-07-14T15:37:04.378864+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n if(nums.length == 3)\n return 0;\n Arrays.sort(nums);\n int last = nums.length-1;\n int ans = Integer.MAX_VALUE;\n for(int i=0;i<=2;i++){\n ans = Math.min(ans , nums[last-i] - nums[2-i]);\n }\n return ans;\n }\n}\n```
0
0
['Array', 'Java']
0
minimum-score-by-changing-two-elements
Two lines is enough
two-lines-is-enough-by-fustigate-3aft
Intuition\nSince we can change two elements to any arbitrary value, we can always change them to be the same value such as the low score is always zero. \n\nNow
Fustigate
NORMAL
2024-07-04T14:21:10.557680+00:00
2024-07-04T14:21:10.557707+00:00
5
false
# Intuition\nSince we can change two elements to any arbitrary value, we can always change them to be the same value such as the low score is always zero. \n\nNow that the low score is out of the way (think of it as simply deleting two elements), we only have to try and minimize the high score to solve the problem. We use the properties of high score: max - min. To decrease this, we need to decrease max and increase min. There are three cases:\n1. we eliminate the first two elements by the method described above (increase min)\n2. we eliminate the last two elements by the method described above (decrease max)\n3. we eliminate the first and last elements by the method described above (increase min and decrease max)\n\n# Code\n```python\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n nums.sort()\n return min(nums[-1] - nums[2], nums[-3] - nums[0], nums[-2] - nums[1])\n```
0
0
['Greedy', 'Python3']
0
minimum-score-by-changing-two-elements
C++ solution with explanation using greedy
c-solution-with-explanation-using-greedy-4r7r
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
roy258
NORMAL
2024-06-17T19:14:20.066634+00:00
2024-06-17T19:14:20.066663+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(nlogn)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int n = nums.size();\n // case 1: take the smallest two numbers and change it than absolute max will be\n int case1 = nums[n-1] - nums[2];\n // case 2: take the gressest two numbers and change it to equal than absolute max would be\n int case2 = nums[n-3] - nums[0];\n // case 3: take the smallest and greatest value and change to equal than absolute max would be\n int case3 = nums[n-2] - nums[1];\n // take minimum of all cases \n return min({case1,case2,case3}); \n }\n};\n```
0
0
['Greedy', 'C++']
0
minimum-score-by-changing-two-elements
Solution with sorting and changing the edges of the array.
solution-with-sorting-and-changing-the-e-82e2
Intuition\n \nEven thought the math in this question looks complex, there are some things to note:\n1. low compelxity doesnt matter, since you can always change
I1FAZEfFom
NORMAL
2024-06-17T07:16:08.294828+00:00
2024-06-17T07:16:08.294865+00:00
2
false
# Intuition\n<!-- \nEven thought the math in this question looks complex, there are some things to note:\n1. low compelxity doesnt matter, since you can always change numbers to the a same number in the array (or just both of them to the same number), resulting it to be 0.\n2. that being said, minimizing the high Score became the task.\n3. to minimize the high score, well need to change 2 out of the 4 edges (maximum, minimum, second maximum, second minimum)\n-->\n\n# Approach\n<!--\nnote: if the array is in the length of 3, the result is always 0, and since my code fails in that specific case, i just added to return 0.\n1. sorting the array\n2. using conditions to determine which 2 of the edges to change.\nnote: once an edge changes, the code doesnt concider it an edge anymore, viewing the next one as the edge.\n\n3. the 2 changed elements are changed to the same number, which is the average of the new edges of the array, to minimize hight score, and setting low score to 0 (they become the same number).\n\n4. once changing them resorting the array to get the score.\n \n-->\n\n# Complexity\n- Time complexity:\n<!-- since im using quickSort, the worst complexity is O(n^2)\n althought average complexity is O(n*log(n))\n -->\n\n- Space complexity:\n<!-- since im using insersionkSort, the worst complexity is O(n^2)\n but since we are using is to sort an almost sorted array, i would say its more like O(n) -->\n\n# Code\n```\npublic class Solution {\n public int MinimizeSum(int[] nums) {\n if(nums.Length == 3)\n return 0;\n int[] arr = QuickSortArray(nums,0,nums.Length-1);\n\n int min = arr[0];\n int min2 = arr[1];\n int max = arr[arr.Length -1];\n int max2 = arr[arr.Length -2];\n\n int min3 = arr[2];\n int max3 = arr[arr.Length-3];\n\n int maxAbsVal = Math.Abs(max3-min3);\n bool isMax = false;\n\n //if(Math.Abs(max - max3) > Math.Abs(min - min3)){\n //isMax = true;\n //}\n\n if(Math.Abs(max - min3) > Math.Abs(min - max3)){\n isMax = true;\n }\n if(isMax){ //max is changing\n if(Math.Abs(min - max3) > Math.Abs(max2 - min2)){\n //min and max are changing\n min = (max2+min2)/2;\n max = min;\n }\n else{\n //max and max2 are changing\n max2 = (min+max3)/2;\n max = min;\n \n }\n }\n else{//min is changing\n if(Math.Abs(max - min3) > Math.Abs(min2 - max2)){\n //min and max are changing\n min = (max2+min2)/2;\n max = min;\n }\n else{\n //min and min2 are changing\n min = (max+min3)/2;\n min2 = min;\n }\n\n\n }\n\n arr[0] = min;\n arr[1] = min2;\n arr[arr.Length -1] = max;\n arr[arr.Length -2] = max2;\n InsersionSort(arr);\n\n return (Math.Abs(arr[arr.Length-1]- arr[0]));\n }\n\n void InsersionSort(int[] arr)\n {\n int n = arr.Length;\n for (int i = 1; i < n; ++i) {\n int key = arr[i];\n int j = i - 1;\n\n // Move elements of arr[0..i-1],\n // that are greater than key,\n // to one position ahead of\n // their current position\n while (j >= 0 && arr[j] > key) {\n arr[j + 1] = arr[j];\n j = j - 1;\n }\n arr[j + 1] = key;\n }\n }\n public int[] QuickSortArray(int[] array, int leftIndex, int rightIndex)\n{\n var i = leftIndex;\n var j = rightIndex;\n var pivot = array[leftIndex];\n\n while (i <= j)\n {\n while (array[i] < pivot)\n {\n i++;\n }\n \n while (array[j] > pivot)\n {\n j--;\n }\n\n if (i <= j)\n {\n int temp = array[i];\n array[i] = array[j];\n array[j] = temp;\n i++;\n j--;\n }\n }\n \n if (leftIndex < j)\n QuickSortArray(array, leftIndex, j);\n\n if (i < rightIndex)\n QuickSortArray(array, i, rightIndex);\n\n return array;\n}\n}\n```
0
0
['C#']
0
minimum-score-by-changing-two-elements
simple 4 line solution
simple-4-line-solution-by-aryan_upadhyay-71gj
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
aryan_upadhyay
NORMAL
2024-06-02T15:07:48.452074+00:00
2024-06-02T15:07:48.452099+00:00
0
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int a=nums[nums.size()-3]-nums[0];\n int b=nums[nums.size()-1]-nums[2];\n int c=nums[nums.size()-2]-nums[1];\n\n return min({a,b,c});\n }\n};\n```
0
0
['C++']
0
minimum-score-by-changing-two-elements
Easy sorting
easy-sorting-by-theberlinbird-bnsr
```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n nums.sort()\n \n p1 = nums[-1] - nums[2]\n p2 = nums[-
theberlinbird
NORMAL
2024-05-01T10:15:58.727978+00:00
2024-05-01T10:15:58.728000+00:00
2
false
```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n nums.sort()\n \n p1 = nums[-1] - nums[2]\n p2 = nums[-3] - nums[0]\n p3 = nums[-2] - nums[1]\n \n return min([p1, p2, p3])\n
0
0
['Sorting', 'Python3']
0
minimum-score-by-changing-two-elements
Simple python3 solution | O(n) time, O(1) memory | 250 ms - faster than 95.89% solutions
simple-python3-solution-on-time-o1-memor-zlfs
Complexity\n- Sorting:\n\n - Time complexity: O(n \cdot \log(n))\n - Space complexity: O(n)\n\n- Using heap:\n\n - Time complexity: O(n \cdot \log(k)) = O(n)
tigprog
NORMAL
2024-04-10T13:00:57.813574+00:00
2024-04-10T13:00:57.813597+00:00
1
false
# Complexity\n- Sorting:\n\n - Time complexity: $$O(n \\cdot \\log(n))$$\n - Space complexity: $$O(n)$$\n\n- Using heap:\n\n - Time complexity: $$O(n \\cdot \\log(k)) = O(n)$$\n - Space complexity: $$O(k) = O(1)$$\n\n\nwhere `k = 3`\n\n# Code\n``` python3 []\n# using sorting\n\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n nums.sort()\n return min(\n nums[-3] - nums[0],\n nums[-2] - nums[1],\n nums[-1] - nums[2],\n )\n```\n``` python3 []\n# using heap\n\nimport heapq\n\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n prefix = heapq.nsmallest(3, nums)\n suffix = heapq.nlargest(3, nums)\n return min(\n suffix[0] - prefix[2],\n suffix[1] - prefix[1],\n suffix[2] - prefix[0],\n )\n```
0
0
['Math', 'Two Pointers', 'Sorting', 'Heap (Priority Queue)', 'Python3']
0
minimum-score-by-changing-two-elements
2 Line Python Solution || Beats 96.67%
2-line-python-solution-beats-9667-by-dod-hnsu
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Dodda_Sai_Sachin
NORMAL
2024-03-19T10:10:03.496579+00:00
2024-03-19T10:10:03.496608+00:00
0
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n nums.sort()\n return min(nums[-3]-nums[0],nums[-1]-nums[2],nums[-2]-nums[1])\n```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
O(N) solution using max/min heap
on-solution-using-maxmin-heap-by-003213-kfj3
Intuition\n\nInstead of sorting whole array, use max/min heap to maintain top 3 largest element and top 3 smallest element.\n\n# Approach\n\n# Complexity\n- Tim
003213
NORMAL
2024-03-02T13:45:19.181420+00:00
2024-03-02T13:45:19.181456+00:00
4
false
# Intuition\n\nInstead of sorting whole array, use max/min heap to maintain top 3 largest element and top 3 smallest element.\n\n# Approach\n\n# Complexity\n- Time complexity:\nO(N)\nBut I don\'t know why this solution takes longer that typical sorting solutions.\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n PriorityQueue<Integer> minHeap = new PriorityQueue<>();\n PriorityQueue<Integer> maxHeap = new PriorityQueue<>(Collections.reverseOrder());\n int n = nums.length;\n \n for(int i=0; i<n; i++) {\n minHeap.add(nums[i]);\n maxHeap.add(nums[i]);\n\n if(minHeap.size() > 3) {\n minHeap.poll();\n maxHeap.poll();\n }\n }\n\n int[] min = new int[3];\n int[] max = new int[3];\n\n for(int i=0; i<3; i++) {\n min[i] = maxHeap.poll();\n max[i] = minHeap.poll();\n }\n\n return Math.min(max[2]-min[0], Math.min(max[1]-min[1], max[0]-min[2]));\n }\n}\n```
0
0
['Java']
0
minimum-score-by-changing-two-elements
Simple solution | Sorting | 3 lines
simple-solution-sorting-3-lines-by-ayush-7mpt
Intuition\nWe are getting a chance to change two numbers, so we can ignore the 1st condition of score, The low score is min(|nums[i] - nums[j]|) for all possibl
ayushannand
NORMAL
2024-02-24T11:10:29.099539+00:00
2024-02-24T11:10:29.099557+00:00
2
false
# Intuition\nWe are getting a chance to change two numbers, so we can ignore the 1st condition of score, `The low score is min(|nums[i] - nums[j]|) for all possible i & j`\nSo, say we are changing `ith` and `jth` indexes we can always make them equal to any other 3rd index, say `k`, to make `low = 0` \nNow we need to minimize high\n\n# Approach\n- Sort the array `nums`\n- Change the largest two element of the array\n - Now our high will be `nums[n-3]-nums[0]`\n - 1,2,3,4,5.........,15,~20,30~\n - ^`nums[0]` . . . . ^`nums[n-3]`\n\n\n- Change the smallest two element of the array\n - Now our high will be `nums[n-1]-nums[2]`\n - ~1,2~,3,4,5.........,15,20,30\n - . . . .^`nums[2]` . . . . . . . ^`nums[n-1]`\n\n\n- Change the largest two element of the array\n - Now our high will be `nums[n-2]-nums[1]`\n - ~1~,2,3,4,5.........,15,20,~30~\n - . . ^`nums[1]` . . . . . ^`nums[n-3]`\n\n\n# Complexity\n- Time complexity: Sorting takes $$O(NLogN)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n``` cpp []\nclass Solution {\npublic:\n int minimizeSum(vector<int>& n) {\n sort(n.begin(),n.end());\n int l = n.size();\n return min(min(n[l-1]-n[2],n[l-3]-n[0]),n[l-2]-n[1]);\n }\n};\n```
0
0
['Math', 'Sorting', 'C++']
0
minimum-score-by-changing-two-elements
simple c++ solution
simple-c-solution-by-spavanii822-z90h
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
spavanii822
NORMAL
2024-01-27T09:26:46.600138+00:00
2024-01-27T09:26:46.600169+00:00
2
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:o(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int n=nums.size();\n int x=nums[n-1]-nums[2];\n int y=nums[n-2]-nums[1];\n int z=nums[n-3]-nums[0];\n int zz= min(x,min(y,z));\n return zz;\n }\n};\n```
0
0
['C++']
0
minimum-score-by-changing-two-elements
O(N) -> 95% | best solution c++
on-95-best-solution-c-by-manaspatidar-hj7m
Intuition\n Describe your first thoughts on how to solve this problem. \nthe min 2 and max 2 elements are responsible to make the high score more high and the l
ManasPatidar
NORMAL
2024-01-21T16:19:24.730456+00:00
2024-01-21T16:19:24.730480+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nthe min 2 and max 2 elements are responsible to make the high score more high and the low score can be set to zero by making two min elements equal\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\napproach 1-> first sort the array and then out of 3 options{\n1-> last element - arr[2]\n2-> arr[size-3] - arr[0]\n3-> arr[size-2] - arr[1]\n}\ndont forget to use absolute values of this 3\nreturn the minimum of 3;\n\napproach 2-> instead of sotring in O(N*Log N), traverse the array and find 3 minimum elements and 3 maximum elements of array and then find min of this 3{\n1-> max1-min3\n2-> max2-min2\n3-> max3-min1\n}\ndont forget to use absolute values of this 3\nreturn minimum of this 3\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& a) {\n // sort(nums.begin(),nums.end());\n int max1=INT_MIN,max2=INT_MIN,min1=INT_MAX,min2=INT_MAX,max3=INT_MIN,min3=INT_MAX;\n for(int i=0;i<a.size();i++){\n if(a[i]>max1){\n max3=max2;\n max2=max1;\n max1=a[i];\n }\n else if(a[i]>max2){\n max3=max2;\n max2=a[i];\n }else if(a[i]>max3){\n max3=a[i];\n }\n if(a[i]<min1){\n min3=min2;\n min2=min1;\n min1=a[i];\n }else if(a[i]<min2){\n min3=min2;\n min2=a[i];\n }\n else if(a[i]<min3){\n min3=a[i];\n }\n }\n return min(abs(max1 - min3),min(abs(max3-min1),abs(max2-min2)));\n }\n};\n```
0
0
['C++']
0
minimum-score-by-changing-two-elements
🚀 Python Short and Fast (93.02%) Solution with friendly explanation 🚀
python-short-and-fast-9302-solution-with-16hd
Intuition\n Describe your first thoughts on how to solve this problem. \n- The first thing to think about after reading the problem is how the low score of nums
john621145
NORMAL
2024-01-21T14:31:47.478573+00:00
2024-01-21T14:31:47.478589+00:00
5
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- The first thing to think about after reading the problem is how the low score of nums is determined and how the high score of nums is determined. The high score of nums will naturally be determined by the smallest and largest numbers in nums. What about low score of nums? How can I create the smallest low score of nums? If there are the same numbers in nums, you can get the smallest score, 0. Having thought this far, we should consider whether we can use `greedy` in this problem.\n\n- Let\'s think about whether `greedy` can be used or not.\n There are two conditions when using `greedy`.\n\n 1. Don\u2019t current choices affect future choices? (Greedy Choice Property)\n 2. When the optimal solutions of the parts are combined, they become the optimal solution of the whole. (Optimal Substructure)\n \n- Let\'s consider what happens the moment we select two elements from nums. At that moment, the high score of nums will be determined. Because we\'re trying to find the lowest score, we won\'t let the two selected elements affect the high score of nums. (It may seem difficult, but you will understand if you look at the solution below.) What should I do with the two elements I selected? We already know the answer. All you have to do is change both elements to an \'appropriate\' number that will not affect the high score of nums and make the low score of nums definitively 0.\n\n- Does this choice satisfy two conditions? Satisfies. The moment we select two elements, the lowest high score of nums is determined. Additionally, by simply changing the two elements selected by \'appropriate\' numbers, the low score of nums can be definitively set to 0 without affecting the high score of nums. Now, while solving the problem, I will explain why the above holds true.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n- We found out that we can take a `greedy` approach in Intuition, and just pick the two elements that produce the smallest high score of nums. To make this easier, we can come up with the idea of sorting nums.\n\n ```\n nums.sort()\n ```\n- Once sorted, we can more easily pick the two elements that produce the smallest high score of nums. Here we have three cases of selecting two elements.\n ```\n 1. Changing first two elements of sorted nums.\n 2. Changing last two elements of sorted nums.\n 3. Changing both ends elements of sorted nums.\n ```\n- If you think about it a little, you can see why these three cases. The high score of nums is the difference between the largest and smallest numbers in nums, so you should focus on both ends of the sorted nums. At this time, the number of cases in which both ends can be changed is the above three methods.\n\n- Now it\'s time to change. However, you can think of it as excluding it rather than changing it. Because, as mentioned above, the two elements you choose to change will each be changed to the same \'appropriate\' number, so you don\'t have to worry about it. A \'appropriate\' number is a number that does not affect either end of the sorted nums, that is, is neither smaller nor larger than the min and max of the sorted nums. Therefore, it does not affect the high score of nums, while the low score of nums is 0. I think you now understand what was explained in Intuition.\n\n- Let\'s find the three high scores of nums using the three methods above.\n ```\n 1. nums[-1]-nums[2] # Excluding first two elements of sorted nums.\n 2. nums[-3]-nums[0] # Excluding last two elements of sorted nums.\n 3. nums[-2]-nums[1] # Excluding both ends elements of sorted nums.\n ```\n- Now you just need to find the min of the three high scores of nums.\n ```\n min(nums[-1]-nums[2],nums[-3]-nums[0],nums[-2]-nums[1])\n ```\n We don\'t need to abs because the nums was sorted and 1 <= nums[i] <= 10^(9).\n ## This is it! All we have to do is return this result.\n\n\n- Additionally, if you want to speed up a bit, you can add a conditional statement.\n ```\n if len(nums) is 3: return 0\n ```\n Did you notice why? Changing two elements to be equal to the remaining elements, the answer is 0.\n There is no need to add this conditional statement, but it shortens runtime.\n\n# Complexity\n- Time complexity\n Timsort `sort()`\nbest case : $$O(n)$$\nworst case : $$O(n log n)$$\n\n\n\n- Space complexity:\nbest case : $$O(1)$$\nworst case : $$O(n)$$\n\n# Code\n```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n if len(nums) is 3: return 0\n nums.sort()\n return min(nums[-1]-nums[2],nums[-3]-nums[0],nums[-2]-nums[1])\n```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
Use PriorityQueue O(n)
use-priorityqueue-on-by-nicholasxie-9xfc
Intuition\nKeep track of largest 3 and smallest 3 elements, one pass.\nThis can be modifed and become full true O(n) by using 6 variables\n# Approach\n Describe
nicholasxie
NORMAL
2024-01-08T07:29:56.856327+00:00
2024-01-08T07:29:56.856346+00:00
3
false
# Intuition\nKeep track of largest 3 and smallest 3 elements, one pass.\nThis can be modifed and become full true O(n) by using 6 variables\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n* lg4 * 2 * 2)\nfor each element we need to insert to PQ then remove from PQ each take lg4\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(6)\n\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n PriorityQueue<Integer> min = new PriorityQueue<Integer>((a, b)->a-b); \n PriorityQueue<Integer> max = new PriorityQueue<Integer>((a, b)->b-a);\n int l=nums[0], r=nums[0];\n for(int x:nums){\n min.add(x);\n max.add(x);\n l=Math.min(l, x);\n r=Math.max(r, x);\n if(min.size()>3)min.poll();\n if(max.size()>3)max.poll();\n }\n int res = Math.min(r-max.peek(), min.peek()-l);\n min.poll();\n max.poll();\n res = Math.min(res, min.peek()-max.peek());\n return res;\n }\n}\n```
0
0
['Java']
0
minimum-score-by-changing-two-elements
easy understand
easy-understand-by-yishurensheng-9npi
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
yishurensheng
NORMAL
2023-12-31T06:01:12.571748+00:00
2023-12-31T06:01:12.571780+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int max1 = INT_MIN, max2 = INT_MIN, max3 = INT_MIN, min1 = INT_MAX, min2 = INT_MAX, min3 = INT_MAX;\n for (auto num : nums) {\n if (max1 < num) {\n max3 = max2;\n max2 = max1;\n max1 = num;\n }\n else if (max2 < num) {\n max3 = max2;\n max2 = num;\n }\n else if (max3 < num) {\n max3 = num;\n }\n\n if (min1 > num) {\n min3 = min2;\n min2 = min1;\n min1 = num;\n }\n else if (min2 > num) {\n min3 = min2;\n min2 = num;\n }\n else if (min3 > num) {\n min3 = num;\n }\n }\n\n // case1 change two max nums\n int ans1 = max3 - min1;\n // case2 change two min nums\n int ans2 = max1 - min3;\n // case3 change one max num and one min num\n int ans3 = max2 - min2;\n int ans = min(ans1, ans2);\n ans = min(ans, ans3);\n\n return ans;\n }\n};\n```
0
0
['C++']
0
minimum-score-by-changing-two-elements
Simple JAVA solution || Easy and Understandable
simple-java-solution-easy-and-understand-3uct
\nThink and Try First\n\n# Code\n\nclass Solution {\n public int minimizeSum(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n
Rohan__1888
NORMAL
2023-12-26T06:50:37.910524+00:00
2023-12-26T06:50:37.910555+00:00
3
false
#\nThink and Try First\n\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n int n = nums.length;\n Arrays.sort(nums);\n int o = nums[n-1] - nums[2];\n int t = nums[n-1-2] - nums[0];\n int h = nums[n-1-1] - nums[1];\n return Math.min(o,Math.min(t,h));\n }\n}\n```
0
0
['Java']
0
minimum-score-by-changing-two-elements
Java | O(N) solution | Beats 100%
java-on-solution-beats-100-by-himanshuck-c50k
Intuition\n\nThe Intuition is first sort the array and then find the minimum between 3 values ->\n\nWe can change 2 elements, and we have to find the absolute v
himanshuckh
NORMAL
2023-11-24T16:18:05.897931+00:00
2023-11-25T17:02:35.278283+00:00
2
false
# Intuition\n\nThe Intuition is first sort the array and then find the minimum between 3 values ->\n\nWe can change 2 elements, and we have to find the absolute value, the minimum would always be 0. So we need to minimze the maximum value.\n\nTo do this, we have sort the array.\n\nNow, once sorted to minimze the maximum value, we have 3 options -\n\nChange the last 2 elements.\nChange the first 2 elements.\nChange the first and the last element\nAnd finally, we get the minimum value\n\n Arrays.sort(nums);\n int a=nums[nums.length-1]-nums[2];\n int b=nums[nums.length-3]-nums[0];\n int c=nums[nums.length-2]-nums[1];\n\n return Math.min(a,Math.min(b,c));\n\nThis code works too, but we can skip the sorting process as well.\nOur end goal is to find 6 elements as we can see above and the indexes.\n\nThe six elements are ->\n\nmin, secondMin, thirdMin\nmax , secondMax , thirdMax;\n\nKeep track of indexes corresponding to the above values\nint a=-1, b=-1, c=-1, d=-1,e=-1,f=-1;\n\nOnce we have these, we can use the same sorting approach as above.\n\n# Complexity\n\nTime complexity:\nO(n)\n\nSpace complexity:\nO(1)\n\nCode\n\n\n# Code\n```\nclass Solution {\n public int minimizeSum(int[] nums) {\n int min = Integer.MAX_VALUE, secondMin = Integer.MAX_VALUE, thirdMin = Integer.MAX_VALUE;\n int max = Integer.MIN_VALUE, secondMax = Integer.MIN_VALUE, thirdMax = Integer.MIN_VALUE;\n int a=-1, b=-1, c=-1, d=-1,e=-1,f=-1;\n\n for(int i=0; i<nums.length; i++) {\n if(max <= nums[i]) {\n a = i;\n max = nums[i];\n }\n if(min >= nums[i]) {\n f = i;\n min = nums[i];\n }\n }\n\n for(int i=0; i<nums.length; i++) {\n if(secondMax <= nums[i] && i != a) {\n b = i;\n secondMax = nums[i];\n }\n if(secondMin >= nums[i] && i != f) {\n e = i;\n secondMin = nums[i];\n }\n }\n\n for(int i=0; i<nums.length; i++) {\n if(thirdMax <= nums[i] && i != a && i!= b) {\n c = i;\n thirdMax = nums[i];\n }\n if(thirdMin >= nums[i] && i != f && i != e) {\n d = i;\n thirdMin = nums[i];\n }\n }\n\n int a1=Math.abs(nums[f]-nums[c]);\n\n int b1=Math.abs(nums[d]-nums[a]);\n\n int c1=Math.abs(nums[e]-nums[b]);\n \n //Return the Min value \n return Math.min(a1,Math.min(b1,c1));\n }\n}\n```
0
0
['Java']
0
minimum-score-by-changing-two-elements
Java 100% faster than all users
java-100-faster-than-all-users-by-yanivc-8ghu
Intuition\nThe high score means the difference between the highest value and the lowest value. The low score means the difference between the two numbers which
yanivcohen
NORMAL
2023-11-12T00:33:00.554745+00:00
2023-11-12T00:33:00.554777+00:00
1
false
# Intuition\nThe high score means the difference between the highest value and the lowest value. The low score means the difference between the two numbers which are closest to each other. The question allows us to change two numbers. We will start by acknowledging that changing two numbers to be the same will result in low score of zero. Meaning we take any two numbers that we like and change them to be like a third number and the low score will be zero. Let\u2019s take an example, num = 1,2,3,4,5,6,7,8,9. The high score is 9 \u2013 1 = 8. The largest minus the smallest. We can change numbers 8,9 to be 7. Resulting in the new num = 1,2,3,4,5,6,7,7,7. This change improve the score two folds. First the low score is zero 7-7. Second the high score is now lower 7 -1 = 6. The idea is to use the ability to change numbers to first reduce the low score to zero, and then reduce the change between the highest and the lowest. In the above example, I have showed how we can reduce the high score by eliminating the two largest numbers. We can try to get the high value and the low value closer to each other in two other ways. We can change the two lowest to the same number as the third lowest. For example 3,3,3,4,5,6,7,8,9. The high score is now 9-3. One more way is to change on one each side. num = 2,2,3,4,5,6,7,8,8.\n\n# Approach\n\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nin place\n\n# Code\n```\nclass Solution {\n \n public static int minimizeSum(int[] nums) {\n //find the lowest 3\n int smallest = Integer.MAX_VALUE;\n int secondSmallest = Integer.MAX_VALUE;\n int thiredSmallest = Integer.MAX_VALUE;\n for(int num : nums){\n if(num < smallest){\n thiredSmallest = secondSmallest;\n secondSmallest = smallest;\n smallest= num;\n }else if(num < secondSmallest){\n thiredSmallest = secondSmallest;\n secondSmallest = num;\n }else if(num < thiredSmallest){\n thiredSmallest = num;\n }\n }\n int largest= Integer.MIN_VALUE;\n int secondLargest = Integer.MIN_VALUE;\n int thiredLargest = Integer.MIN_VALUE;\n for(int num : nums){\n if(num >largest){\n thiredLargest = secondLargest;\n secondLargest = largest;\n largest= num;\n }else if(num > secondLargest){\n thiredLargest = secondLargest;\n secondLargest = num;\n }else if(num > thiredLargest){\n thiredLargest = num;\n }\n }\n //System.out.println("smallest " + smallest + " second smallest " + secondSmallest + " Third smallest " + thiredSmallest);\n //System.out.println("largest " + largest + " second largest " + secondLargest + " Third largest " + thiredLargest);\n return Math.min(Math.min(thiredLargest - smallest, largest - thiredSmallest),secondLargest-secondSmallest);\n\n }\n}\n```
0
0
['Java']
0
minimum-score-by-changing-two-elements
O(n) | Easy to Understand | Golang
on-easy-to-understand-golang-by-drafttin-qg8b
Suppse max1, max2, max3 represent the three largest numbers, and min1, min2 and min3 represent the three smallest numbers. By modifying two elements in the arra
drafttin
NORMAL
2023-11-05T13:14:50.013641+00:00
2023-11-05T13:14:50.013658+00:00
7
false
Suppse max1, max2, max3 represent the three largest numbers, and min1, min2 and min3 represent the three smallest numbers. By modifying two elements in the array. We can reduce the score to *min(max1 - min3, max3 - min1, max2 - min2)*\n\n# Code\n```\nfunc minimizeSum(nums []int) int {\n max1, max2, max3 := math.MinInt32, math.MinInt32, math.MinInt32\n min1, min2, min3 := math.MaxInt32, math.MaxInt32, math.MaxInt32\n for _, num := range nums {\n if num > max1 {\n max3 = max2\n max2 = max1\n max1 = num\n } else if num > max2 {\n max3 = max2\n max2 = num\n } else if num > max3 {\n max3 = num\n }\n\n if num < min1 {\n min3 = min2\n min2 = min1\n min1 = num\n } else if num < min2 {\n min3 = min2\n min2 = num\n } else if num < min3 {\n min3 = num\n }\n }\n return min(min(max1 - min3, max3 - min1), max2 - min2)\n}\n\n\n```
0
0
['Go']
0
minimum-score-by-changing-two-elements
Python. Easy code, using sorting
python-easy-code-using-sorting-by-zhanar-7jgs
\n# Approach\n We are trying to minimize the difference between elements, so we are checking the edges of the sorted array. \n\n\n# Code\n\nclass Solution:\n
zhanara
NORMAL
2023-10-31T07:53:59.524110+00:00
2023-10-31T07:53:59.524131+00:00
3
false
\n# Approach\n We are trying to minimize the difference between elements, so we are checking the edges of the sorted array. \n\n\n# Code\n```\nclass Solution:\n def minimizeSum(self, nums: List[int]) -> int:\n nums = sorted(nums)\n return min(nums[-1]-nums[2], nums[-3]-nums[0], nums[-2]-nums[1])\n```
0
0
['Python3']
0
minimum-score-by-changing-two-elements
Easy taking all cases possible
easy-taking-all-cases-possible-by-napan-84yr
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
napan
NORMAL
2023-10-18T03:58:28.241985+00:00
2023-10-18T03:58:28.242014+00:00
1
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int ans=abs(nums[0]-nums.back());\n //left 2\n ans=(ans,abs(nums.back()-nums[2]));\n //right 2\n ans=min(ans,abs(nums[0]-nums[nums.size()-3]));\n //one left one right\n ans=min(ans,abs(nums[1]-nums[nums.size()-2]));\n return ans;\n } \n};\n```
0
0
['C++']
0
minimum-score-by-changing-two-elements
Easy taking all cases possible
easy-taking-all-cases-possible-by-napan-osgx
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
napan
NORMAL
2023-10-18T03:58:04.769464+00:00
2023-10-18T03:58:04.769493+00:00
0
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int ans=abs(nums[0]-nums.back());\n //left 2\n ans=(ans,abs(nums.back()-nums[2]));\n //right 2\n ans=min(ans,abs(nums[0]-nums[nums.size()-3]));\n //one left one right\n ans=min(ans,abs(nums[1]-nums[nums.size()-2]));\n return ans;\n } \n};\n```
0
0
['C++']
0
minimum-score-by-changing-two-elements
Easy C++ 2 liner code
easy-c-2-liner-code-by-aryangarg0729-35i0
Complexity\n- Time complexity:O(nlogn)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity:O(1)\n Add your space complexity here, e.g. O(n) \n\n#
aryangarg0729
NORMAL
2023-10-04T09:41:26.041663+00:00
2023-10-04T09:41:26.041681+00:00
4
false
# Complexity\n- Time complexity:$$O(nlogn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n return min(min(nums[nums.size()-1]-nums[2],nums[nums.size()-3]-nums[0]),nums[nums.size()-2]-nums[1]);\n }\n};\n// [1,1,3,4,5,8]\n// [1,4,5,7,8]\n// [8,28,42,58,75]\n```
0
0
['Greedy', 'Sorting', 'C++']
0
minimum-score-by-changing-two-elements
easy 3 steps solution
easy-3-steps-solution-by-sonu781-xr7z
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
Sonu781
NORMAL
2023-09-19T07:07:21.944828+00:00
2023-09-19T07:07:21.944872+00:00
3
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(nlogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n sort(nums.begin(),nums.end());\n int n = nums.size();\n int a = nums[n-3] - nums[0];\n int b = nums[n-1] - nums[2];\n int c = nums[n-2] - nums[1];\n return min(a,min(b,c));\n }\n};\n```
0
0
['C++']
0
minimum-score-by-changing-two-elements
C++ Simple Solution using sorting
c-simple-solution-using-sorting-by-ujjwa-hnp8
Complexity\n- Time complexity:\nO(n log n)\n- Space complexity:\nO(1)\n\n# Code\n\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n
ujjwal141
NORMAL
2023-08-28T18:56:00.767696+00:00
2023-08-28T18:56:26.907319+00:00
7
false
# Complexity\n- Time complexity:\nO(n log n)\n- Space complexity:\nO(1)\n\n# Code\n```\nclass Solution {\npublic:\n int minimizeSum(vector<int>& nums) {\n int n = nums.size();\n sort(nums.begin(), nums.end());\n \n // nums[0] = nums[n-1], nums[1]=a[n-1] for mx1\n int mx1 = abs(nums[n-1]-nums[2]);\n\n // nums[n-2] = nums[0], nums[n-1]=nums[0] for mx2\n int mx2 = abs(nums[n-3]-nums[0]);\n \n // nums[n-1] = nums[n-2], nums[0]=nums[1] for mx3\n int mx3 = nums[n-2]-nums[1];\n \n // min is always 0.\n\n return min(mx1, min(mx2, mx3));\n }\n};\n```
0
0
['Sorting', 'C++']
0
minimum-insertion-steps-to-make-a-string-palindrome
[Java/C++/Python] Longest Common Sequence
javacpython-longest-common-sequence-by-l-2zpa
Intuition\nSplit the string s into to two parts,\nand we try to make them symmetrical by adding letters.\n\nThe more common symmetrical subsequence they have,\n
lee215
NORMAL
2020-01-05T04:01:48.044745+00:00
2020-01-10T03:06:47.692895+00:00
33,278
false
## **Intuition**\nSplit the string `s` into to two parts,\nand we try to make them symmetrical by adding letters.\n\nThe more common symmetrical subsequence they have,\nthe less letters we need to add.\n\nNow we change the problem to find the length of longest common sequence.\nThis is a typical dynamic problem.\n<br>\n\n## **Explanation**\n**Step1.**\nInitialize `dp[n+1][n+1]`,\nwhere`dp[i][j]` means the length of longest common sequence between\n`i` first letters in `s1` and `j` first letters in `s2`.\n\n**Step2.**\nFind the the longest common sequence between `s1` and `s2`,\nwhere `s1 = s` and `s2 = reversed(s)`\n\n**Step3.**\n`return n - dp[n][n]`\n<br>\n\n## **Complexity**\nTime `O(N^2)`\nSpace `O(N^2)`\n<br>\n\n**Java:**\n```java\n public int minInsertions(String s) {\n int n = s.length();\n int[][] dp = new int[n+1][n+1];\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n dp[i + 1][j + 1] = s.charAt(i) == s.charAt(n - 1 - j) ? dp[i][j] + 1 : Math.max(dp[i][j + 1], dp[i + 1][j]);\n return n - dp[n][n];\n }\n```\n\n**C++:**\n```cpp\n int minInsertions(string s) {\n int n = s.length();\n vector<vector<int>> dp(n + 1, vector<int>(n + 1));\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n dp[i + 1][j + 1] = s[i] == s[n - 1 - j] ? dp[i][j] + 1 : max(dp[i][j + 1], dp[i + 1][j]);\n return n - dp[n][n];\n }\n```\n\n**Python:**\nNote that `~j = -j - 1`\n```python\n def minInsertions(self, s):\n n = len(s)\n dp = [[0] * (n + 1) for i in xrange(n + 1)]\n for i in xrange(n):\n for j in xrange(n):\n dp[i + 1][j + 1] = dp[i][j] + 1 if s[i] == s[~j] else max(dp[i][j + 1], dp[i + 1][j])\n return n - dp[n][n]\n```\n
301
6
[]
36
minimum-insertion-steps-to-make-a-string-palindrome
[C++] Simple DP (Memoization) and Bottom-up with O(n) Space
c-simple-dp-memoization-and-bottom-up-wi-51en
Observation\nLet\'s imagine matching the characters of the string like a palindrome, from the begining and the end with 2 pointers i and j.\nWe may encounter 2
phoenixdd
NORMAL
2020-01-05T04:00:58.122845+00:00
2024-11-25T04:01:34.105622+00:00
17,592
false
**Observation**\nLet\'s imagine matching the characters of the string like a palindrome, from the begining and the end with 2 pointers `i` and `j`.\nWe may encounter 2 scenarios:\n1) The character at `i` matches character at `j`.\n2) The characters don\'t match each other\n\nIn case of 1 we just increase the pointer `i` and decrease the pointer `j`, `i++` and `j--` respectively.\n\nIn the second case we have 2 options:\n1) Insert one character at `j` to match the character at `i`.\n\nOr\n\n2) Insert one character at `i` to match the character at `j`.\n\nSince we are not actually adding the characters in the string but just calculating the cost,\nIn case 1 we increase the pointer `i` by `1` and `j` stays as it is, as we still need a character to match at `j`\nand in case 2 we decrease the pointer `j` by `1` and `i` stays as it is, as we still need a character to match at `i`.\nboth the cases adds cost `1` since we are inserting a letter.\n\nWe can then use these two different pairs of new `i` and `j` values (`i+1, j` and `i, j-1`) to again repeat the process and use the **minimum** result of these as our result for current pair of `i, j`.\nWe can see that this is recursive and thus we can use recursion with caching to store the repeated values.\n\n**Solution (Memoization)**\n```c++\nclass Solution {\npublic:\n vector<vector<int>> memo;\n int dp(string &s,int i,int j) {\n if(i>=j)\t\t\t\t\t\t\t//Base case.\n return 0;\n if(memo[i][j]!=-1)\t\t\t\t\t//Check if we have already calculated the value for the pair `i` and `j`.\n return memo[i][j];\n return memo[i][j]=s[i]==s[j]?dp(s,i+1,j-1):1+min(dp(s,i+1,j),dp(s,i,j-1));\t\t//Recursion as mentioned above.\n }\n int minInsertions(string s) {\n memo.resize(s.length(),vector<int>(s.length(),-1));\n return dp(s,0,s.length()-1);\n }\n};\n```\n**Complexity**\nSpace: `O(n^2)` as we can store at max all possible pairs of `i` and `j`.\nTime: `O(n^2)` as we calculate all pairs of possible `i` and `j`.\n\n**Note:** Space complexity can be reduced to `O(n)` by using bottom-up DP and storing only the previous state. (As we can see from the recursion, we only need `i-1` or `j-1` at any given point.)\n\n**Solution (Bottom-up)** \nAs I mentioned in the **Note** earlier, that we can reduce the space complexity as we only need the previous `i+1` or `j-1` states, I thought why not just add the solution as well. So here goes.\n\nWe can be cognizant of how we fill the `memo` table to optimize the space complexity when we have such scenarios. The code is pretty self explanatory with the added comments.\n```c++\nclass Solution {\npublic:\n int minInsertions(string s) {\n vector<int> memo(s.length(),0);\n int prev,temp;\n for(int i=s.length()-2;i>=0;i--) {\n prev=0; //This stores the value at memo[i+1][j-1];\n for(int j=i;j<s.length();j++) {\n temp=memo[j]; //Get the value of memo[i+1][j].\n memo[j]=s[i]==s[j]?prev:1+min(memo[j],memo[j-1]); //memo[j]=memo[i+1][j], memo[j-1]=memo[i][j-1], prev=memo[i+1][j-1].\n prev=temp; //Store the value of memo[i+1][j] to use it as memo[i+1][j-1] in the next iteration.\n }\n }\n return memo[s.length()-1];\n }\n};\n```\n**Complexity**\nSpace: `O(n)` as we reuse the previously stored value from previous state from the `memo` or `prev` variable.\nTime: `O(n^2)` as we calculate all pairs of possible `i` and `j`.
222
5
['Dynamic Programming', 'Memoization', 'C++']
21
minimum-insertion-steps-to-make-a-string-palindrome
516. Longest Palindromic Subsequence
516-longest-palindromic-subsequence-by-v-rad5
If we figure out the longest palindromic subsequence, then we can tell the miminum number of characters to add or remove to make the string a palindrome. \n\nSo
votrubac
NORMAL
2020-01-05T04:03:33.868440+00:00
2021-04-06T17:22:48.665695+00:00
11,484
false
If we figure out the longest palindromic subsequence, then we can tell the miminum number of characters to add or remove to make the string a palindrome. \n\nSo, we can simply reuse [516. Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/).\n```CPP\nint minInsertions(string s) {\n return s.size() - longestPalindromeSubseq(s);\n}\nint dp[501][501] = {};\nint longestPalindromeSubseq(string &s) {\n for (int len = 1; len <= s.size(); ++len)\n for (int i = 0; i + len <= s.size(); ++i) \n dp[i][i + len] = s[i] == s[i + len - 1] ? dp[i + 1][i + len - 1] + (len == 1 ? 1 : 2) \n : max(dp[i][i + len - 1], dp[i + 1][i + len]);\n return dp[0][s.size()];\n}\n```
118
4
[]
14
minimum-insertion-steps-to-make-a-string-palindrome
✅✅Python🔥Java 🔥C++🔥Simple Solution🔥Easy to Understand🔥
pythonjava-csimple-solutioneasy-to-under-dmr4
Please UPVOTE \uD83D\uDC4D\n\n!! BIG ANNOUNCEMENT !!\nI am Giving away my premium content videos related to computer science and data science and also will be s
cohesk
NORMAL
2023-04-22T00:07:36.886825+00:00
2023-04-22T13:16:20.902755+00:00
15,936
false
# Please UPVOTE \uD83D\uDC4D\n\n**!! BIG ANNOUNCEMENT !!**\nI am Giving away my premium content videos related to computer science and data science and also will be sharing well-structured assignments and study materials to clear interviews at top companies to my first 10,000 Subscribers. So, **DON\'T FORGET** to Subscribe\n\n# **Search \uD83D\uDC49`Tech Wired leetcode`**\n\n# Video Solution\n\n# **Search \uD83D\uDC49`Minimum Insertion Steps to Make a String Palindrome by Tech Wired`**\n\n# OR \n# **Click the Link in my Leetcode Profile**\n\n![Yellow & Black Earn Money YouTube Thumbnail (19).png](https://assets.leetcode.com/users/images/fb32a329-d572-4f87-bc55-3b1147e81722_1682127595.149926.png)\n\n\n# Approach:\n\nThe problem can be solved using dynamic programming. We can create a 2D table dp, where dp[i][j] represents the minimum number of insertions required to make the substring s[i:j+1] a palindrome. The base case is when i=j, where the substring is already a palindrome and no insertions are needed. If s[i] == s[j], then the substring is already a palindrome and we can use the result of dp[i+1][j-1]. Otherwise, we need to insert either a character at index i or j to make them equal, so we take the minimum of dp[i+1][j] and dp[i][j-1] and add 1 to it.\n\nWe can fill the table dp using a bottom-up approach. We start with the smallest substrings (length 1) and work up to the entire string. The final answer is stored in dp[0][n-1], where n is the length of the input string s.\n\nHowever, we can further optimize the space complexity of the solution by using only one row of the 2D table dp at a time. We can iterate over the columns of the table in reverse order and update the row accordingly. By updating the row in reverse order and using a variable to store the previous value of dp[j], we avoid overwriting the values in the row before they are used in the current iteration.\n\n# Intuition:\n\nThe problem requires us to find the minimum number of insertions needed to make a string palindrome. We can approach this by breaking down the string into smaller substrings and computing the minimum number of insertions needed for each substring.\n\nIf we consider a substring s[i:j+1], we can make it a palindrome by inserting characters at the beginning or end of the substring. We can use dynamic programming to solve the problem by breaking down the string into smaller substrings and computing the minimum number of insertions needed for each substring. By computing the minimum number of insertions needed for each substring, we can find the minimum number of insertions needed to make the entire string palindrome.\n\nThe dynamic programming solution uses a 2D table to store the minimum number of insertions needed for each substring. By breaking down the string into smaller substrings and using the results of the smaller substrings to compute the results of the larger substrings, we can find the minimum number of insertions needed to make the entire string palindrome.\n\n```Python []\nclass Solution:\n def minInsertions(self, s: str) -> int:\n n = len(s)\n dp = [0] * n\n for i in range(n - 2, -1, -1):\n prev = 0\n for j in range(i + 1, n):\n temp = dp[j]\n if s[i] == s[j]:\n dp[j] = prev\n else:\n dp[j] = min(dp[j], dp[j-1]) + 1\n prev = temp\n return dp[n-1]\n```\n```Java []\nclass Solution {\n public int minInsertions(String s) {\n int n = s.length();\n int[] dp = new int[n];\n for (int i = n - 2; i >= 0; i--) {\n int prev = 0;\n for (int j = i + 1; j < n; j++) {\n int temp = dp[j];\n if (s.charAt(i) == s.charAt(j)) {\n dp[j] = prev;\n } else {\n dp[j] = Math.min(dp[j], dp[j-1]) + 1;\n }\n prev = temp;\n }\n }\n return dp[n-1];\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int minInsertions(string s) {\n int n = s.length();\n vector<int> dp(n);\n for (int i = n - 2; i >= 0; i--) {\n int prev = 0;\n for (int j = i + 1; j < n; j++) {\n int temp = dp[j];\n if (s[i] == s[j]) {\n dp[j] = prev;\n } else {\n dp[j] = min(dp[j], dp[j-1]) + 1;\n }\n prev = temp;\n }\n }\n return dp[n-1];\n }\n};\n\n```\n
90
2
['String', 'Dynamic Programming', 'C++', 'Java', 'Python3']
1
minimum-insertion-steps-to-make-a-string-palindrome
Using LCS 🔥 C++🔥Simple Explanation 🔥Easy approach 🔥
using-lcs-csimple-explanation-easy-appro-4j9r
PLEASE UPVOTE \uD83D\uDC4D\n# Approach\n- ##### To make a string s palindrome, we need to add characters to the string such that it becomes the same when read f
ribhav_32
NORMAL
2023-04-22T00:31:16.081993+00:00
2023-04-22T00:36:51.099654+00:00
6,787
false
# **PLEASE UPVOTE \uD83D\uDC4D**\n# Approach\n- ##### To make a string s palindrome, we need to add characters to the string such that it becomes the same when read from both sides. \n- ##### The idea is to find the LCS between the original string s and its reverse string s\'. The length of LCS will give us the number of characters that are already palindrome in s. We can subtract this length from the length of s to get the number of characters we need to add to make s palindrome.\n- ##### Let dp[i][j] be the length of the longest common subsequence between the first i characters of string A and the first j characters of string B. We can fill up the table using the following recurrence relation:\n 1. ##### If A[i-1] == B[j-1], then dp[i][j] = dp[i-1][j-1] + 1, because the ith and jth characters match and contribute to the LCS.\n 2. ##### If A[i-1] != B[j-1], then dp[i][j] = max(dp[i-1][j], dp[i][j-1]), because the ith and jth characters do not match and we have two options: either skip the ith character of A or skip the jth character of B.\n- ##### The final answer will be stored in dp[m][n], where m and n are the lengths of the input strings A and B, respectively.\n\n# Intuition\n- ##### The intuition behind using the LCS algorithm to find the minimum number of steps to make a string palindrome is based on the fact that a palindrome string is symmetric around its center.\n\n- ##### Let\'s consider an example string "abcd". To make it a palindrome, we can add characters "d", "c", "b" to the beginning of the string to get "dcbaabcd", which is a palindrome. Alternatively, we can add characters "a", "b", "c" to the end of the string to get "abcddcba", which is also a palindrome.\n\n- ##### In general, to make a string palindrome, we need to add characters to either the beginning or the end of the string to make it symmetric around its center. The center of the string is the middle character(s) if the length of the string is odd, or the two middle characters if the length of the string is even.\n\n# Complexity\n- Time complexity: O(n^2)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n^2)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# **PLEASE UPVOTE \uD83D\uDC4D**\n# Code\n```\nclass Solution {\npublic:\n int lcs(string t, string s, vector<vector<int>>&dp){\n int n = s.size();\n for(int i = 0; i <= n; i++){\n for(int j = 0; j <= n; j++){\n if(i == 0 || j == 0)\n dp[i][j] = 0;\n }\n }\n\n for(int i = 1; i <= n; i++){\n for(int j = 1; j <= n; j++){\n if(s[i-1] == t[j-1]){\n dp[i][j] = 1 + dp[i-1][j-1];\n } else{\n dp[i][j] = max(dp[i-1][j],dp[i][j-1]);\n }\n }\n }\n return dp[n][n];\n }\n \n int minInsertions(string s) {\n string t = s;\n reverse(t.begin(),t.end());\n int n = s.size();\n vector<vector<int>>dp(n+1,vector<int>(n+1,0));\n return n - lcs(s,t,dp);\n }\n};\n```\n![e2515d84-99cf-4499-80fb-fe458e1bbae2_1678932606.8004954.png](https://assets.leetcode.com/users/images/13c32ead-4eb5-472d-8301-8e78d3bcc3c5_1682123350.7417476.png)\n\n
48
0
['String', 'Dynamic Programming', 'C++']
1
minimum-insertion-steps-to-make-a-string-palindrome
[Java/Python 3] DP - longest common subsequence w/ brief explanation and analysis.
javapython-3-dp-longest-common-subsequen-ea5a
Q & A:\n\nQ: Can you please explain more how exactly lcs with its reverse helps?\nA: An example could be illustrative. e.g., "mbadm". Let\'s mark the characters
rock
NORMAL
2020-01-05T04:01:49.500516+00:00
2023-04-22T13:34:56.726064+00:00
6,432
false
**Q & A:**\n\nQ: Can you please explain more how exactly lcs with its reverse helps?\nA: An example could be illustrative. e.g., "mbadm". Let\'s mark the characters not in LCS:\n"m`b`a`d`m"\nReverse:\n"m`d`a`b`m"\nWe need at least 2 insertions - `b` and `d` - to make them palindromes:\n"m`bd`a`db`m" or\n"m`db`a`bd`m"\n\n**End of Q & A**\n\n----\n\nPlease refer to my solution [Java/Python 3 2 Clean DP codes of O(m * n) & O(min(m, n)) space w/ breif explanation and analysis](https://leetcode.com/problems/max-dot-product-of-two-subsequences/discuss/649858/JavaPython-3-2-Clean-DP-codes-of-O(mn)-and-O(min(m-n))-space-w-breif-explanation-and-analysis.) of a similar problem: [1458. Max Dot Product of Two Subsequences](https://leetcode.com/problems/max-dot-product-of-two-subsequences/description/)\n\nMore similar LCS problems:\n[1092. Shortest Common Supersequence](https://leetcode.com/problems/shortest-common-supersequence/) and [Solution](https://leetcode.com/problems/shortest-common-supersequence/discuss/312757/JavaPython-3-O(mn)-clean-DP-code-w-picture-comments-and-analysis.)\n[1062. Longest Repeating Substring](https://leetcode.com/problems/longest-repeating-substring/) (Premium).\n[516. Longest Palindromic Subsequence](https://leetcode.com/problems/longest-palindromic-subsequence/)\n[1312. Minimum Insertion Steps to Make a String Palindrome](https://leetcode.com/problems/minimum-insertion-steps-to-make-a-string-palindrome/discuss/470709/JavaPython-3-DP-longest-common-subsequence-w-brief-explanation-and-analysis)\n\n----\nFind the size of the longest common subsequence between the original string and its reverse, deduct it from the size of the original string, that is the solution.\n```java\n public int minInsertions(String s) {\n String r = new StringBuilder(s).reverse().toString();\n return s.length() - lcs(s, r);\n }\n private int lcs(String s, String r) {\n int n = s.length();\n int[][] dp = new int[n + 1][n + 1];\n for (int i = 0; i < n; ++i)\n for (int j = 0; j < n; ++j)\n dp[i + 1][j + 1] = s.charAt(i) == r.charAt(j) ? dp[i][j] + 1 : Math.max(dp[i + 1][j], dp[i][j + 1]);\n return dp[n][n]; \n }\n\n```\n\n```python\n def minInsertions(self, s: str) -> int:\n def lcs(s: str, r: str) -> int:\n n = len(r)\n dp = [[0] * (n + 1) for _ in range(n + 1)]\n for i, a in enumerate(s):\n for j, b in enumerate(r):\n dp[i + 1][j + 1] = dp[i][j] + 1 if a == b else max(dp[i][j + 1], dp[i + 1][j])\n return dp[n][n]\n return len(s) - lcs(s, s[::-1])\n```\n**Analysis:**\nTime & space: `O(n ^ 2)`, where n = `s.length()`.\n\n----\n\nSpace optimization:\n\n```java\n public int minInsertions(String s) {\n return s.length() - lcs(s, new StringBuilder(s).reverse().toString());\n }\n private int lcs(String s, String r) {\n int n = s.length();\n int[][] dp = new int[2][n + 1];\n for (int i = 0; i < n; ++i) {\n for (int j = 0; j < n; ++j) {\n dp[1 - i % 2][j + 1] = s.charAt(i) == r.charAt(j) ? 1 + dp[i % 2][j] : Math.max(dp[1 - i % 2][j], dp[i % 2][j + 1]);\n }\n }\n return dp[n % 2][n]; \n }\n```\n```python\n def minInsertions(self, s: str) -> int:\n \n def lcs(s: str, r: str) -> int:\n n = len(s)\n dp = [[0] * (n + 1) for _ in range(2)]\n for i, c in enumerate(s):\n for j, d in enumerate(r):\n dp[1 - i % 2][j + 1] = 1 + dp[i % 2][j] if c == d else max(dp[i % 2][j + 1], dp[1 - i % 2][j])\n return dp[n % 2][n]\n \n return len(s) - lcs(s, s[:: -1])\n```\n**Analysis:**\nTime: `O(n ^ 2)`, space: `O(n)`, where `n = s.length()`.\n
39
1
['Dynamic Programming', 'Java', 'Python3']
5
minimum-insertion-steps-to-make-a-string-palindrome
[C++] Intuition & Explanation Recursion To Iteration With Codes
c-intuition-explanation-recursion-to-ite-cy75
INTUITION\n Rather than thinking of it from some other problem(LCS, which most have done), I feel that it is better to visualize it as a new problem. \n When tr
gagandeepahuja09
NORMAL
2020-01-05T04:17:38.854477+00:00
2020-01-05T04:40:05.845826+00:00
2,980
false
# INTUITION\n* Rather than thinking of it from some other problem(LCS, which most have done), I feel that it is better to visualize it as a new problem. \n* When trying to check if palindrome or building a palindrome, we start from start and end chars of string\n* If chars are same, we could change it to a subproblem from both sides.\n\t**f(i, j) = f(i + 1, j - 1)**\n* On the other hand, if they are different characters, we have 2 options. Either to **add a character at ith index = s[j] or add a character at jth index = s[i]**. The minimum of these two would give our required answer.\n\n\n```\n\t// Recursive Approach\n\tint f(string s, int i, int j, vector<vector<int>>& dp) {\n if(i >= j)\n return 0;\n if(dp[i][j] != -1)\n return dp[i][j];\n if(s[i] == s[j])\n return dp[i][j] = f(s, i + 1, j - 1, dp);\n int op1 = 1 + f(s, i + 1, j, dp);\n int op2 = 1 + f(s, i, j - 1, dp);\n return dp[i][j] = min(op1, op2); \n }\n```\t\n\t\n# \tRecursion To Iteration\n* Since, i is dependent on i + 1 (next value) and j on j - 1(previous value), then how can we write an iterative dp code?\n* We can see that we need to calculate our answer for smaller lengths first. We can precompute for len = 0 and then while increasing length, we will have our answer for all smaller length. Assume an index i, then j = i + len.\n\t\n ``` \n int minInsertions(string s) {\n vector<vector<int>> dp(s.size(), vector<int>(s.size(), 1e6));\n int n = s.size();\n for(int i = 0; i < n; i++)\n dp[i][i] = 0;\n for(int len = 1; len <= n; len++) {\n for(int i = 0; i + len < n; i++) {\n dp[i][i] = 0;\n int j = i + len;\n if(s[i] == s[j]) {\n if(len == 1)\n dp[i][j] = 0;\n else\n dp[i][j] = dp[i + 1][j - 1];\n }\n else {\n dp[i][j] = min(1 + dp[i + 1][j], 1 + dp[i][j - 1]);\n }\n }\n }\n return dp[0][n - 1];\n }\n};\n```
37
1
[]
5
minimum-insertion-steps-to-make-a-string-palindrome
[Java] Longest Common Subsequence Solution - Clean code
java-longest-common-subsequence-solution-avsr
Idea\n- If we know the longest palindromic sub-sequence is x and the length of the string is n then, what is the answer to this problem? It is n - x as we need
hiepit
NORMAL
2020-01-05T04:01:11.025146+00:00
2021-07-13T02:47:38.432117+00:00
2,813
false
**Idea**\n- If we know the longest palindromic sub-sequence is `x` and the length of the string is `n` then, what is the answer to this problem? It is `n - x` as we need `n - x` insertions to make the remaining characters also palindrome.\n\n```java\nclass Solution {\n public int minInsertions(String s) {\n String sReverse = new StringBuilder(s).reverse().toString();\n int lcs = longestCommonSubsequence(s.toCharArray(), sReverse.toCharArray());\n return s.length() - lcs;\n }\n\n private int longestCommonSubsequence(char[] arr1, char[] arr2) {\n int n1 = arr1.length, n2 = arr2.length;\n int[][] dp = new int[n1 + 1][n2 + 1];\n for (int i = 1; i <= n1; i++) {\n for (int j = 1; j <= n2; j++) {\n if (arr1[i - 1] == arr2[j - 1]) {\n dp[i][j] = dp[i - 1][j - 1] + 1;\n } else {\n dp[i][j] = Math.max(dp[i - 1][j], dp[i][j - 1]);\n }\n }\n }\n return dp[n1][n2];\n }\n}\n```\nComplexity:\n- Time: `O(n^2)`, `n` is the length of string `s`\n- Space: `O(n^2)`
31
1
[]
6
minimum-insertion-steps-to-make-a-string-palindrome
✔️✔️Easy Solutions in Java ✔️✔️, Python ✔️, and C++ ✔️🧐Look at once 💻 with Exaplanation
easy-solutions-in-java-python-and-c-look-nft5
Intuition\n Describe your first thoughts on how to solve this problem. \n>To make a given string s a palindrome, we need to insert characters at some positions
Vikas-Pathak-123
NORMAL
2023-04-22T06:30:51.401617+00:00
2023-04-22T06:30:51.401661+00:00
1,743
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n>To make a given string `s` a palindrome, we need to insert characters at some positions in the string. If we can find the longest common subsequence (LCS) between the given string `s` and its reverse, we can find the characters that are already part of the palindrome. Then, we can insert the remaining characters (which are not part of the LCS) at their appropriate positions in the string to make it a palindrome.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Reverse the input string to get a new string `reversed_s`.\n2. Initialize a 2D array `dp` of size `(n+1)x(n+1)` with 0s, where `n` is the length of the input string `s`.\n3. Iterate through all pairs of indices `(i,j)` of the array `dp`, where `1<=i,j<=n`.\n4. If the characters at indices `i-1` in string `s` and `j-1` in `reversed_s` are equal, set `dp[i][j] = dp[i-1][j-1] + 1`.\n5. Otherwise, set `dp[i][j]` to the maximum of `dp[i-1][j]` and `dp[i][j-1]`.\n6. The length of the LCS between `s` and `reversed_s` is `dp[n][n]`.\n7. The minimum number of insertions required to make `s` a palindrome is `n - dp[n][n]`\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n>O(n^2), where `n` is the length of the input string `s`. This is because we are filling up a 2D array of size `(n+1)x(n+1)` using dynamic programming approach.\n\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n>O(n^2), where `n` is the length of the input string `s`. This is because we are using a 2D array of size `(n+1)x(n+1)` to store the LCS of substrings.\n\n\n![image.png](https://assets.leetcode.com/users/images/b427e686-2e5d-469a-8e7a-db5140022a6b_1677715904.0948765.png)\n\n\n# Please Upvote\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution.\uD83D\uDE0A Keep Learning\nPlease give my solution an upvote! \uD83D\uDC4D\nIt\'s a simple way to show your appreciation and\nkeep me motivated. Thank you! \uD83D\uDE0A\n```\n\n\n# Code\n```java []\nclass Solution {\n public int minInsertions(String s) {\n // reverse the input string\n String reversed = new StringBuilder(s).reverse().toString();\n // get the length of the input string\n int n = s.length();\n // create a 2D array to store the LCS of substrings\n int[][] dp = new int[n+1][n+1];\n \n // fill up the dp array using dynamic programming approach\n for(int i=1; i<=n; i++) {\n for(int j=1; j<=n; j++) {\n if(s.charAt(i-1) == reversed.charAt(j-1)) {\n // if characters match, add 1 to LCS\n dp[i][j] = dp[i-1][j-1] + 1;\n } else {\n // otherwise, take maximum LCS of two substrings\n dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);\n }\n }\n }\n \n // return the minimum number of insertions required to make s a palindrome\n // this is the difference between the length of s and the length of its LCS\n return n - dp[n][n];\n }\n}\n\n```\n```python []\nclass Solution(object):\n def minInsertions(self, s):\n # reverse the input string\n reversed_s = s[::-1]\n # get the length of the input string\n n = len(s)\n # create a 2D array to store the LCS of substrings\n dp = [[0 for j in range(n+1)] for i in range(n+1)]\n \n # fill up the dp array using dynamic programming approach\n for i in range(1, n+1):\n for j in range(1, n+1):\n if s[i-1] == reversed_s[j-1]:\n # if characters match, add 1 to LCS\n dp[i][j] = dp[i-1][j-1] + 1\n else:\n # otherwise, take maximum LCS of two substrings\n dp[i][j] = max(dp[i-1][j], dp[i][j-1])\n \n # return the minimum number of insertions required to make s a palindrome\n # this is the difference between the length of s and the length of its LCS\n return n - dp[n][n]\n```\n```C++ []\nclass Solution {\npublic:\n int minInsertions(string s) {\n // reverse the input string\n string reversed_s = string(s.rbegin(), s.rend());\n // get the length of the input string\n int n = s.length();\n // create a 2D vector to store the LCS of substrings\n vector<vector<int>> dp(n+1, vector<int>(n+1, 0));\n \n // fill up the dp vector using dynamic programming approach\n for(int i=1; i<=n; i++) {\n for(int j=1; j<=n; j++) {\n if(s[i-1] == reversed_s[j-1]) {\n // if characters match, add 1 to LCS\n dp[i][j] = dp[i-1][j-1] + 1;\n } else {\n // otherwise, take maximum LCS of two substrings\n dp[i][j] = max(dp[i-1][j], dp[i][j-1]);\n }\n }\n }\n \n // return the minimum number of insertions required to make s a palindrome\n // this is the difference between the length of s and the length of its LCS\n return n - dp[n][n];\n }\n};\n```\n\n``` javascript []\n/**\n * @param {string} s\n * @return {number}\n */\nvar minInsertions = function(s) {\n // reverse the input string\n const reversedS = s.split(\'\').reverse().join(\'\');\n // get the length of the input string\n const n = s.length;\n // create a 2D array to store the LCS of substrings\n const dp = Array.from({ length: n + 1 }, () => new Array(n + 1).fill(0));\n \n // fill up the dp array using dynamic programming approach\n for(let i = 1; i <= n; i++) {\n for(let j = 1; j <= n; j++) {\n if(s[i-1] === reversedS[j-1]) {\n // if characters match, add 1 to LCS\n dp[i][j] = dp[i-1][j-1] + 1;\n } else {\n // otherwise, take maximum LCS of two substrings\n dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);\n }\n }\n }\n \n // return the minimum number of insertions required to make s a palindrome\n // this is the difference between the length of s and the length of its LCS\n return n - dp[n][n];\n};\n\n```\n```\nLCS stands for Longest Common Subsequence\n```\n\n# Please Comment\uD83D\uDC4D\uD83D\uDC4D\n```\nThanks for visiting my solution comment below if you like it.\uD83D\uDE0A\n```
23
2
['Dynamic Programming', 'Python', 'C++', 'Java', 'JavaScript']
0