环形数组中的最大贡献值

77 阅读1分钟

问题描述

小S拿到了一个长度为 nn 的环形数组,并定义了两个下标 ii 和 jj 的贡献值公式为:
f(i, j) = (a_i + a_j) × dist(i, j)
其中 dist(i, j) 是下标 ii 和 jj 在数组中的最短距离。小S希望找到一对下标,使得它们的贡献值尽可能大。环形数组的特点是最左和最右的元素也是相邻的。你需要帮助她找到最大贡献值。

例如,给定数组 [1, 2, 3],由于是环形数组,任意两个下标的距离都是1,因此 f(2,3)=(2+3)×1=5f(2,3)=(2+3)×1=5。

输入:

  • n : 数组长度
  • a : 环形数组

约束条件:

  • n >= 1
  • 1 <= a[i] <= 1000

测试样例

样例1:

输入:n = 3,a = [1, 2, 3]
输出:5

样例2:

输入:n = 4,a = [4, 1, 2, 3]
输出:12

样例3:

输入:n = 5,a = [1, 5, 3, 7, 2]
输出:24

public class Main {
     public static int solution(int n, int[] a) {
        // PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
        // write code here
        if(n<2){
            return 0;
        }
        int i,limit,j,ans=Integer.MIN_VALUE,tmp=0;
        limit=n/2;

        for(i=0;i<n;i++){
            for(j=1;j<=limit;j++){
                tmp=j*(a[i]+a[(i+j)%n]);
                if(tmp>ans){
                    ans=tmp;
                }
            }
        }

        //System.out.println(ans);
        return ans; // Placeholder return
    }
    public static void main(String[] args) {
        System.out.println(solution(3, new int[]{1, 2, 3}) == 5);
        System.out.println(solution(4, new int[]{4, 1, 2, 3}) == 12);
        System.out.println(solution(5, new int[]{1, 5, 3, 7, 2}) == 24);
    }
}