网易编程题:疯狂队列(序列相邻元素之差的绝对值和最大)

#include

#include

using namespace std;

int func(vector &height){

int n = height.size();

sort(height.begin(),height.end(),less());

int lastMax = height[n-1];

int lastMin = height[0];

int sum =  lastMax - lastMin;

int curMinIndex = 1,curMaxIndex = n - 2;

/*每次从数组中选取最大最小元素和新序列中最大最小元素交错做差*/

while(curMinIndex < curMaxIndex){

sum += lastMax - height[curMinIndex];

sum += height[curMaxIndex] - lastMin;

lastMin = height[curMinIndex];

lastMax = height[curMaxIndex];

++curMinIndex;

--curMaxIndex;

}

/*如果有奇数个元素,最后curMinIndex = curMaxIndex*/

if(curMinIndex == curMaxIndex){

sum = max(sum + abs(height[curMinIndex] - lastMin),sum + abs(height[curMaxIndex] - lastMax));

}

return  sum;

}

int main(){

int n;

while(cin >> n){

vector height(n);

for(auto i = 0;i < n;++i)

cin>>height[i];

cout<

}

    return 0;

}

你可能感兴趣的:(网易编程题:疯狂队列(序列相邻元素之差的绝对值和最大))