解題步驟:
1. 從頭開始,紀錄到每一個位置的最大值 ( max_from_head )
2. 從尾開始,紀錄到每一個位置的最小值 ( min_from_tail )
每一個極大差距發生在,max_from_head[i] - min_from_tail[i+1]
找出之中最大的差距即為答案
#include <iostream>
using namespace std;
#define N 100000
int input_number[N];
int max_from_head[N];
int min_from_tail[N];
int main()
{
int n;
cin >> n;
for(int i = 0; i<n; i++)
cin >> input_number[i];
/* set max */
max_from_head[0] = input_number[0];
for(int i = 1; i<n; i++)
input_number[i] > max_from_head[i-1] ? max_from_head[i] = input_number[i] : max_from_head[i] = max_from_head[i-1];
/* set min */
min_from_tail[n-1] = input_number[n-1];
for(int i = n-2; i>=0; i--)
input_number[i] < min_from_tail[i+1] ? min_from_tail[i] = input_number[i] : min_from_tail[i] = min_from_tail[i+1];
/* find answer */
int answer = 0;
for(int i = n-2; i>=0; i--)
if( max_from_head[i] - min_from_tail[i+1] > answer )
answer = max_from_head[i] - min_from_tail[i+1];
cout << answer << endl;
return 0;
}
留言列表