【发布时间】:2019-09-20 11:54:51
【问题描述】:
If you know the future prices of a stock, what's the best time to buy and sell? 也有类似的问题,但并不完全相同。
给定:一个整数数组代表一个项目的股票价格 问题:如果我们在第 X 天卖出一股,然后在第 X+n 天卖出,找到最大可能的收益。
我写了一个函数:
- 假设 maxPossibleBenefit 可以在第 2 天完成:
1.1 maxPossibleBenefit = a[1] - a[0]
- 从a[0]遍历数组到a[a.length -1]:
2.1 如果a[X+n] - a[X] > maxPossibleBenefit,则maxPossibleBenefit = a[X+n] - a[X]。
3.当X+n == a.length(我们到达数组的末尾)时,从a[1]开始重复步骤2和2.1,然后从a[2]开始,直到我们到达a.[length- 2] 比较最后 2 个元素。
public static int maxBenefit(int[] arr) {
//first, assuming that max benefit can be received on day 2
int maxBenefit = arr[1] - arr[0];
// traverse the entire array and check,
// will we get more benefit if we buy on day one
// and sell on day 2, 3, up until the last day in the range:
for (int i = 0; i < arr.length - 1; i++) {
// with every run we shift purchase date by one into the future
for (int j = i; j < arr.length - 1; j++) {
// if we sell later than on day 2, will we get more benefit?
if ((arr[j + 1] - arr[j]) > maxBenefit)
maxBenefit = arr[j + 1] - arr[j];
}
}
return maxBenefit;
}
但是对于数组 {8, 6, 5, 6, 7, 9, 10, 7, 9, 4},函数返回 2,而它应该是 5 (a[6] - a[2])。
您能帮我找出算法中的缺陷吗?
【问题讨论】:
-
你试过用调试器运行它吗?
-
其实没有,我还没学会怎么用。是的,真丢脸。