求波峰波谷最大值

给一个数组,求它的最大的波峰波谷的落差。

举例:数组  A={2, 3, 6, 5, 7, 9}, 其中 6 和 9 被看做是波峰,2和5则是波谷。D[2, 6]=4, D[6,5]=1, D=[5,9]=4. 则 Thus, MaxD(A)=4.

 

 

    public static void main(String[] args) {
        int[] nums = new int[]{1, 2, 3, 4, 5, 7};
        System.out.println(calPeekToTroughDiff(nums));
    }

    public static int calPeekToTroughDiff(int[] nums) {
        if (nums == null || nums.length < 2) {
            return 0;
        }
        int result = Integer.MIN_VALUE;
        int peak = nums[0], trough = nums[0];
        for (int i = 1; i < nums.length; ++i) {
            if (nums[i] >= nums[i - 1]) {
                peak = nums[i];
            } else {
                trough = nums[i];
            }
            if (peak - trough > result) {
                result = peak - trough;
            }
        }
        return result;
    }

 

你可能感兴趣的:(Java,算法)