最大线性股票得分
难度:
标签:
题目描述
代码结果
运行时间: 120 ms, 内存: 37.5 MB
/*
* Leetcode 2898 - Maximum Linear Stock Score
*
* Problem Statement:
* Given an array of stock prices, find the maximum score by selecting a subarray and summing up its elements.
*
* Approach using Java Stream:
* - We can use Java Stream to process the array and calculate the maximum subarray sum.
* - Use a custom collector to keep track of the current and maximum scores while traversing the array.
*/
import java.util.stream.IntStream;
public class MaxLinearStockScoreStream {
public int maxScore(int[] prices) {
return IntStream.of(prices).collect(() -> new int[]{0, 0},
(acc, price) -> {
acc[0] = Math.max(0, acc[0] + price);
acc[1] = Math.max(acc[1], acc[0]);
},
(acc1, acc2) -> {
acc1[0] = Math.max(acc1[0], acc2[0]);
acc1[1] = Math.max(acc1[1], acc2[1]);
})[1];
}
public static void main(String[] args) {
MaxLinearStockScoreStream solution = new MaxLinearStockScoreStream();
int[] prices = {1, -2, 3, 10, -4, 7, 2, -5};
System.out.println(solution.maxScore(prices)); // Output: 18
}
}
解释
方法:
这道题解的核心思路是基于转换后的差值来归类和计算得分。具体来说,对于数组中的每个元素 prices[i],我们计算出 p - i 的差值(即 prices[i] - i),这个差值用作字典 d 的键。这个字典 d 的值是该差值对应所有 prices[i] 的总和。算法的关键在于,如果两个价格的差值相等,即 prices[i] - i == prices[j] - j,那么这两个位置可以构成一对有效的组合。我们通过字典记录下每个差值的总和,最后返回字典中最大的值,即为最大线性股票得分。
时间复杂度:
O(n)
空间复杂度:
O(n)
代码细节讲解
🦆
为什么在计算得分时选择使用差值 `prices[i] - i` 作为字典的键?这种方法有什么特别的意义或优势吗?
▷🦆
在题解中提到,如果两个价格的差值相等,则这两个位置可以构成一对有效的组合。这里的“有效组合”是指什么?能否具体解释一下这种组合的意义或用途?
▷🦆
题解中提到的字典 `d` 最终存储的是差值对应的价格总和,但是这是否意味着所有具有相同差值的元素都被视为等效?这种处理方式存在哪些潜在的问题或限制?
▷