# 趣味算法-求波峰波谷最大值

2 3 6 5 7 9
2 3 6 5 7
2 3 6 5 7 9 10

#include <iostream>

using namespace std;

void scanPeak(int arr[], int length, int* pvlst)
{
int i = 0;
int curr_peak = 0;
int curr_val = 0;
bool is_continue = true;

for (i = 1; i < length-1; i++)
{
if ((arr[i] < arr[i-1]) && (arr[i] < arr[i+1]))
{
pvlst[i] = -1;
}
else if ((arr[i] > arr[i-1]) && (arr[i] > arr[i+1]))
{
pvlst[i] = 1;
}
}

if (arr[0] < arr[1])
pvlst[0] = -1;
else if (arr[0] > arr[1])
pvlst[0] = 1;

if (arr[length-1] < arr[length-2])
pvlst[length-1] = -1;
else if (arr[length-1] > arr[length-2])
pvlst[length-1] = 1;
}

void maxNeighboringPeak(int arr[], int length)
{
int i = 0;
int * pvlst = NULL;
int peak = 0;
int vall = 0;
int pair = 0;
int max = 0;

pvlst = new int[length];
memset(pvlst, 0, sizeof(int)*length);

scanPeak(arr, length, pvlst);

for (i = 0; i < length; i++)
{
cout << pvlst[i] << "  ";
}
cout << endl << endl;

for (i = 0; i < length; i++)
{
if (pvlst[i] == 1)
{
peak = i;
pair++;
}

if (pvlst[i] == -1)
{
vall = i;
pair++;
}

if (2 == pair)
{
pair = 0;
if (arr[peak]-arr[vall] > max)
max = arr[peak]-arr[vall];
}
}

cout << max << endl;

delete[] pvlst;
pvlst = NULL;
}

int main()
{
//int arr[6] = {2, 3, 6, 5, 7, 9};
//int arr[5] = {2, 3, 6, 5, 7};
int arr[7] = {2, 3, 6, 5, 7, 9, 10};

int length = sizeof(arr)/sizeof(arr[0]);

maxNeighboringPeak(arr, length);

cout<<endl;

cin >> length;
return 0;
}

-1  0  1  -1  0  0  1

5

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120