java 股票类最大收益问题 求助 急

zoufan2010 2018-04-30 10:16:57
在股市的交易日中,假设最多可进行两次买卖(即买和卖的次数均小于等于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];
}
}

但是输出结果老是不一样
请问是否有别的方法记录时间
...全文
1118 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

67,512

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧