求整数列中存在的最大差值

问题描述:给定一行整数,其中最后一个数字为其个数,在O(n)的时间里求该整数列中存在的最大差值,并且只能拿右边的数减去左边的数。

例如:10  -5  3  3   ,  最大差值为 8 = 3 - (-5);

10  5  2   ,  最大差值为 0 = 10 - 10  或者 5 - 5.

实现代码如下(Java版):

import java.util.Scanner;
/*
 * 在O(n)的时间里计算一个包含n个数字的数组中的最大差值,其中只能拿右边数减左边数
 * 例如,10,5的最大差值是0 = 10 - 10 或者 5 - 5
 */
public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String str = in.nextLine();
        String[] arr = str.split("\s");
        int n = Integer.parseInt(arr[arr.length-1]);
        int[] num = new int[n];
        for(int i=0;i<n;i++)
            num[i] = Integer.parseInt(arr[i]);
        System.out.println(getResult(n,num));
        in.close();
    }
    
    public static int getResult(int n,int[] num){
        int result = Integer.MIN_VALUE;
        int left = 0,right = 0;
        while(left<=right&&right<n){
            if(num[right]<num[left])
                left = right;
            int temp = num[right]-num[left];
            if(temp>result)
                result = temp;
            right++;
        }
        return result;
    }
}
原文地址:https://www.cnblogs.com/JiaJoa/p/7793780.html