最快就是直接create一個array然後造作
但省空間還有個方法, 我們可以知道最後平衡的值一定是中間那個數
而我們只要從index 0 加到這個target 間的總合加起來即可, 空間複雜度只有O(1)
class Solution {
public:
int minOperations(int n) {
int target = 0;
if(n % 2 == 0){
target = (n / 2) + ((n - 1) / 2) + 1;
}else{
target = (n / 2) * 2 + 1;
}
int res = 0;
for(int i = 0; i * 2 + 1 < target; i++){
int num = i * 2 + 1;
res += target - num;
}
return res;
}
};