21.环形数组中的最大贡献值<字节青训营-中等题>

87 阅读1分钟

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

2.思路

穷举,看每一对下标的贡献值哪个最大

3.代码

#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <string>
#include <cmath>    // 引入 cmath 以使用 std::abs

using namespace std;

int solution(int n, std::vector<int> a) {
    // PLEASE DO NOT MODIFY THE FUNCTION SIGNATURE
    // write code here
    int max_contribute = 0;
    for (int i = 0; i < a.size(); i++) {
        for (int j = i + 1; j < a.size(); j++) {
            int distance = std::abs(i - j);  // i 和 j 的距离
            max_contribute = max(max_contribute, (a[i] + a[j]) * min(j - i, i + n - j));
        }
    }
    return max_contribute; // Placeholder return
}

int main() {
    std::cout << solution(3, {1, 2, 3});
    std::cout << (solution(3, {1, 2, 3}) == 5) << std::endl;
    std::cout << (solution(4, {4, 1, 2, 3}) == 12) << std::endl;
    std::cout << (solution(5, {1, 5, 3, 7, 2}) == 24) << std::endl;
    return 0;
}

注意:环形数组中两个数之间的距离分别为j - ii + n - j(j > i)