问题描述
小M的任务是调整一只股票的价格,使其符合一个给定的正整数序列p0,p1,…,pn−1p0,p1,…,pn−1,并且要确保每个月的股票上涨系数不能超过某个百分比kk。
上涨系数定义为当月价格相对于之前所有月份价格总和的比例。如果上涨系数超过k%k%,就需要对某些月份的价格进行调整,以尽量减少对整体序列的变更。
你需要输出在保证上涨系数不超过k%k%的情况下,最少需要增加的价格总和。
测试样例
样例1:
输入:
n = 5,k = 12,p = [1000, 34, 12, 27, 131]
输出:19
样例2:
输入:
n = 4,k = 10,p = [100, 1, 1, 1]
输出:0
样例3:
输入:
n = 6,k = 15,p = [500, 50, 30, 20, 10, 60]
输出:0
样例分析
- 输入:`n = 5, k = 12, p = [1000, 34, 12, 27, 131]`
- 输出:19
- 过程:
- 月1:总价 = 1000
- 月2:总价 = 1034
- 月3:总价 = 1046
- 月4:总价 = 1073
- 月5:总价 = 1223,需要增加19
- **样例2**:
- 输入:`n = 4, k = 10, p = [100, 1, 1, 1]`
- 输出:0
- 过程:
- 月1:总价 = 100
- 月2:总价 = 101
- 月3:总价 = 102
- 月4:总价 = 103
- **样例3**:
- 输入:`n = 6, k = 15, p = [500, 50, 30, 20, 10, 60]`
- 输出:0
- 过程:
- 月1:总价 = 500
- 月2:总价 = 550
- 月3:总价 = 580
- 月4:总价 = 600
- 月5:总价 = 610
- 月6:总价 = 670
代码分享
public class Main {
public static int solution(int n, int k, int[] p) {
int totalPrice = 0; // 初始化总价格
int totalIncrease = 0; // 初始化总增加价格
double maxIncreaseFactor = (double) k / 100; // 最大上涨系数
for (int i = 0; i < n; i++) {
if (i == 0) {
totalPrice += p[i]; // 初始化 totalPrice
continue; // 跳过第一次循环的上涨系数计算
}
double currentIncreaseFactor = (double) p[i] / totalPrice; // 计算当前上涨系数
if (currentIncreaseFactor > maxIncreaseFactor) {
// 计算需要增加的价格
int requiredIncrease = (int) Math.ceil((p[i] / maxIncreaseFactor - totalPrice));
requiredIncrease = Math.max(requiredIncrease, 1); // 确保 requiredIncrease 至少为1
totalIncrease += requiredIncrease; // 更新总增加价格
p[i] += requiredIncrease; // 更新当前月份价格
}
totalPrice += p[i]; // 更新总价格
}
return totalIncrease; // 返回总增加价格
}
public static void main(String[] args) {
int[] arr1 = {1000, 34, 12, 27, 131};
int[] arr2 = {100, 1, 1, 1};
int[] arr3 = {500, 50, 30, 20, 10, 60};
System.out.println("Sample 1: Total Increase: " + solution(5, 12, arr1) + " (Expected: 19)");
System.out.println("Sample 2: Total Increase: " + solution(4, 10, arr2) + " (Expected: 0)");
System.out.println("Sample 3: Total Increase: " + solution(6, 15, arr3) + " (Expected: 0)");
}
}
总结
-
初始化变量:
totalPrice和totalIncrease初始化为0。maxIncreaseFactor计算为k / 100。
-
遍历每个月的价格:
- 对于第一个月,直接将价格加入
totalPrice。 - 对于后续每个月,计算当前价格上涨系数
currentIncreaseFactor。 - 如果
currentIncreaseFactor超过maxIncreaseFactor,计算需要增加的价格requiredIncrease,确保增加后的价格使上涨系数刚好不超过最大值。 - 更新
totalIncrease和当前月份的价格p[i]。 - 更新
totalPrice。
- 对于第一个月,直接将价格加入
-
计算
requiredIncrease:- 使用公式
requiredIncrease = (int) Math.ceil((p[i] / maxIncreaseFactor - totalPrice))确保计算出的requiredIncrease能使上涨系数刚好不超过maxIncreaseFactor。
- 使用公式