最大銷售增幅
任務描述
本關任務:編寫函數 maxIncrease,用於計算一個銷售額序列中的最大銷售增幅並返回。這里的銷售額都是非負整數。
對於給定的銷售額序列 A,假設序列 A 的長度為 n( n >= 2 ),最大銷售額增幅是指滿足0 <= x <= y < n
的A[y] - A[x]
的最大值。
例如,銷售額序列11,3,5,7,9,2,4,6,8,10
的最大增幅為88(在 x=5 , y=9 時)。
測試樣例
測試輸入:6 12 34 78 45 10 23
(第一個數據表示有66天的銷售額分,剩下的數據為具體額分)
預期輸出:最大銷售增幅為:66
測試輸入:9 90 2 80 3 70 6 50 7 40
預期輸出:最大銷售增幅為:78
源代碼
#include <iostream>
using namespace std;
// 函數maxIncrease:計算銷售額增幅
// 參數:s-銷售額數組,n-銷售額數組長度,n>1
// 返回值:銷售額最大增幅
int maxIncrease(int s[], int n);
int main()
{
int n, a[30], i; // 定義變量及數組,n-銷售額個數,a-銷售額數組
cin >> n; // 輸入銷售額數量,n>1
// 輸入n個銷售額,分別存入a[0]到a[n-1]
for(i = 0; i < n; i++)
cin >> a[i];
i = maxIncrease(a,n);
cout << "最大銷售增幅為:" << i << endl;
return 0;
}
int maxIncrease(int s[], int n)
{
//請在此添加代碼,實現函數maxIncrease
/********** Begin *********/
int i,j,max=s[1]-s[0];
for(i = 0; i <= n-2; i++){
for(j=i+1;j<=n-1;j++){
if(s[j]-s[i]>max){
max=s[j]-s[i];
}
}
}
return max;
/********** End **********/
}