Python | Brute-force with Optimized code | Fastest | Simple | EXPLAINED
Maths formula used? \n1) Sum of first n even numbers = n(n+1)\n2) Sum of first n odd numbers = n * n\n\nLet\'s consider 2 scenarios:\n1) n is odd:\nExample : n=
Maths formula used? \n1) Sum of first n even numbers = n(n+1)\n2) Sum of first n odd numbers = n * n\n\nLet\'s consider 2 scenarios:\n1) n is odd:\nExample : n=6\nArray: 1, 3, 5, 7, 9, 11, 13\nIn order to make all the values same, it\'s easiest to pick the middle element and make all the elements same as that.\nSo, in one operation, let\'s pick one element from left side of middle and one element from right side of middle.\nFor our example: middle element = 7\n1st operation: Let\'s pick 5 on left and 9 on right. Operations: 5+1 and 9-1 (as only we can add/subtract by 1 for 2 elements at once)\nArray: 1, 3, 6, 7, 8, 11, 13\n2nd operation: 6+1 and 8-1\nArray: 1, 3, 7, 7, 7, 11, 13\nLike you can see, we had to use 2 operations to make 5 and 9 on either side of 7 to make it equal to 7. No. of operations = middle - current element\nSo for next steps, we need 4 operations to make 3 same as 7 and another 6 operations for 1 to be 7.\n\nIf we see the pattern: If we select middle element as 7. \nThese are the number of operations: 6 operations for 1, 4 operations for 3, 2 operations for 5 \nThe pattern is as follows (reverse): 2, 4, 6 \nIf n is odd, the pattern is of even numbers. As we already know formula for sum of even numbers = n(n+1)\nNumber of elements in above pattern = n/2 \nSo *sum = n/2(n/2 + 1)*\n\n2) n is even:\n\nSimilarly, let\'s take an example with even number of elements:\nArray: 1, 3, 5, 7, 9, 11\nMiddle element =? not there, 5, 7 are in middle, so it is wise to change all elements to 6\nIf we check patterns for operations it will be: 1, 3, 5     (6-5, 6-3, 6-1)\nIt is a pattern of odd numbers.\nSum formula is nxn\nIn pattern we see half the elements i.e. n/2\n*Ans: n/2 x n/2*\n\nSo algo for code:\n1) Find the number of elements in pattern ? mid = n/2\n2) For even n, pattern is of odd numbers. Ans: n/2 x n/2\n3) For odd n, patterm is of even numbers. Ans: n/2 x (n/2 + 1)\n```\nclass Solution:\n    def minOperations(self, n: int) -> int:\n        # first_val = 1\n        # end_val = 2*(n-1)+1\n        # target_val = (first_val+end_val)//2\n        # diff1 = (target_val - first_val)//2\n        # steps = diff1*(diff1+1)\n        # while first_val < target_val:\n        #     steps = steps + (target_val - first_val)\n        #     first_val = first_val + 2\n        mid = n//2\n        if n%2 != 0:\n            return mid*(mid+1)\n        else:\n            return mid*mid\n            \n            \n        \n```
[]