题解 | 牛牛与切割机-Java

牛牛与切割机

https://www.nowcoder.com/practice/cda06078a54142d29da7adc3b9ad5880

设做序列和为x,总序列和为常数k,则右序列和为k-x;

即问题可等价为:求y=x(k-x)=-x^2+xk的最小值,抛物线开口向下,则其最小值必在两个端点处取得。

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        long[] arr = new long[n];
        long totalSum = 0; // 存储序列总元素和
        
        // 读取序列元素并计算总 sum
        for (int i = 0; i < n; i++) {
            arr[i] = in.nextInt();
            totalSum += arr[i];
        }
        
        // 计算两个端点切割的代价
        // 切割点1:左序列仅含第1个元素,右序列含剩余n-1个元素
        long cost1 = arr[0] * (totalSum - arr[0]);
        // 切割点2:左序列含前n-1个元素,右序列仅含最后1个元素
        long cost2 = (totalSum - arr[n - 1]) * arr[n - 1];
        
        // 取两个代价的最小值作为结果
        long minCost = Math.min(cost1, cost2);
        System.out.println(minCost);
        
        in.close(); 
    }
}

全部评论

相关推荐

10-13 13:49
南京大学 财务
饿魔:笑死我了,你简直是个天才
点赞 评论 收藏
分享
双尔:你就写拥有ai开发经历,熟练运用提示词,优化ai,提高ai回答质量
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务