天津大學OJ_2017_07_12比賽I題L-The math problem

L-The math problem

Description:

Given an array a with n intergers, please tell me the max(aj−ai),0≤i≤j≤n−1.

Input:

The input consists of multiple test cases. The first line contains an integer T, indicating the number of test cases.(1≤T≤1000)
Each case contains one integer N.(0≤N≤10^7). Then comes a line with N intergers ai(−10^7≤ai≤10^7)

Output:

For each case only output the answer.

Sample Input:

1
5
1 3 5 4 2 

Sample Output:

4

題目意思:

就是給你n個數,然後讓你找max{aj-ai},其中j>=i的。

思路:

  • 首先我們要知道我們最好只能掃一遍就能求出。所以要不斷更新最小值和最大差值。

  • 可以這樣想,我們從第一個數開始掃,得到當前值 a[i] ,當遇到比我們當前最小值 minNum 更小的就更新最小值 minNum = a[i] 。這一步執行完後,還要用當前數 a[i] 減去當前最小值 minNum ,得到當前的差值 tempX ,如果當前差值大於當前最大差值 maxNum , 就更新最大差值maxNum。

  • 當我們遇到一個更小的數的時候,就應該更新最小值,以後都是當前值減去最小值這樣得到的差值肯定比當前值減去上一次的最小值要大。同時我們得到的差值也需要比較,比當前最大差值大我們才更新,這樣一直下去就可以再後面的數減去前面的數的前提下得到最大差值。

AC代碼:

    #include<iostream>
    #include<cstdio>
    #include<vector>
    #include<set>
    #include<algorithm>
    #include<cmath>
    using namespace std;

    int a[10000010];

    int main()
    {
        int T;
        scanf("%d",&T);
        while(T--)
        {
            int n;
            int max = 0;
            int minNum = 1 << 30; 
            scanf("%d",&n);
            for(int i=0;i<n;i++)
                scanf("%d",&a[i]);

            //開始掃
            for(int i = 0;i<n;i++)
            {
                if(a[i] < minNum)      //更新最小值
                    minNum = a[i];

                if(a[i] - minNum > max)  //更新最大差值
                    max = a[i] - minNum;    
            } 
            printf("%d\n",max); 
        } 
        return 0;
    } 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章