牛客 — 左右最值最大差

左右最值最大差

牛客网链接

题的内容:给定一个长度为N(N>1)的整型数组A,可以将A划分成左右两个部分,左部分A[0..K],右部分A[K+1..N-1],K可以取值的范围是[0,N-2]。求这么多划分方案中,左部分中的最大值减去右部分最大值的绝对值,最大是多少?
测试方案:

[2,7,3,1,1],5

返回:6

代码实现

import java.util.*;

public class MaxGap {
    
    
    public int findMaxGap(int[] A, int n) {
    
    
        // write code here
        int max = 0;
        for(int i = 0;i <= n-2;i++){
    
    
            max = Math.max(max,Math.abs(getMax(A,0,i)-getMax(A,i+1,n-1)));
        }
        return max;
    }
    public static int getMax(int[] arr,int start,int end){
    
    
        int max = arr[end];
        for(int i = start;i < end;i++){
    
    
            max = Math.max(max,arr[i]);
        }
        return max;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_45665172/article/details/113704283
今日推荐