//左右最值最大差

本文介绍了一种求解数组中左右两侧最大值差的方法。通过遍历数组,分别找出左侧最大值和右侧最大值,然后计算两者之间的差值,最终返回所有差值中的次大值。此算法涉及数组操作、排序和比较过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import java.util.Arrays;
//左右最值最大差
public class Main_251 {
    public static int findMaxGap(int[] A, int n) {
        // write code here
        int[] max = new int[n - 1];
        int k = 0;
        int max1 = 0;
        int max2 = 0;
        for (int i = 1; i < n; i++) {
            int[] A1 = new int[i];
            for (int j = 0; j < i; j++) {
                A1[j] = A[j];
            }
            Arrays.sort(A1);
            max1 = A1[i - 1];

            int[] A2 = new int[n - i];
            for (int j = 0; j < n - i; j++) {
                A2[j] = A[i + j];
            }
            Arrays.sort(A2);
            max2 = A2[n - i - 1];

            max[k] = ((max1 - max2) > 0) ? (max1 - max2) : (max2 - max1);
            k++;
        }
        Arrays.sort(max);
        return max[n - 2];
    }

    public static void main(String[] args) {
        int[] A = {2,7,3,1,1,8};
        int n = A.length;
        int s = findMaxGap(A, n);
        System.out.println(s);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值