java 股票类最大收益问题 求助 急
在股市的交易日中,假设最多可进行两次买卖(即买和卖的次数均小于等于2),规则是必须一笔成交后进行另一笔(即买-卖-买-卖的顺序进行)。给出一天中的股票变化序列,请写一个程序计算一天可以获得的最大收益。请采用实践复杂度低的方法实现。
这是我的代码
public static float maxProfix(float[] prices, int n) {
if (prices.length < 2) return 0;
float[] preProfit = new float[n];
float[] postProfit = new float[n];
float curMin = prices[0];
for (int i = 1; i < n; i++) {
curMin = Math.min(curMin, prices[i]);
preProfit[i] = Math.max(preProfit[i - 1], prices[i] - curMin);
}
float curMax = prices[n - 1];
for (int i = n - 2; i >= 0; i--) {
curMax = Math.max(curMax, prices[i]);
postProfit[i] = Math.max(postProfit[i + 1], curMax - prices[i]);
}
float maxProfit = 0;
for (int i = 0; i < n; i++) {
maxProfit = Math.max(maxProfit, preProfit[i] + postProfit[i]);
System.out.println(i);
System.out.println(preProfit[i]);
System.out.println(postProfit[i]);
System.out.println(maxProfit);
}
return maxProfit;
后来又要要求要知道两次买入卖出的具体时间
我就把max改写成if语句想要记录下 时间的移动
float curMax = prices[n - 1];
for (int i = n - 2; i >= 0; i--) {
curMax = Math.max(curMax, prices[i]);
postProfit[i] = Math.max(postProfit[i + 1], curMax - prices[i]);
}
我改写成if形式想要记录i
for (int i = n-2; i>=0; i--) {
if(array[i]==0)
{
i--;
postprofit[i]=postprofit[i+1];
}
if(array[i]>array[max]) {
max=i;
maxnum = array[i];
postprofit[i] = postprofit[i+1];
}
if((maxnum-array[i])>postprofit[i+1])
{
postprofit[i] = maxnum-array[i];
}
else{
postprofit[i] = postprofit[i+1];
}
}
但是输出结果老是不一样
请问是否有别的方法记录时间