您的位置:首页 > 其它

算法-股票交易最大收益

2018-03-14 11:34 429 查看
题目描述
在股市的交易日中,假设最多可进行两次买卖(即买和卖的次数均小于等于2),规则是必须一笔成交后进行另一笔(即买-卖-买-卖的顺序进行)。给出一天中的股票变化序列,计算一天可以获得的最大收益。

遍历算法(复杂度较高)public class MaxProfit {
public static void main(String[] args) {
int samples[] = {10,22,50,75,65,80};
int len = samples.length;
System.out.println(calcMaxProfit(samples, 0, len-1));
}

/**
* 计算最多两次买卖最大收益
*
* @param p_samples: 样本数组;
* @param startIndex: 样本数组开始索引;
* @param endIndex: 样本数组结束索引;
*
* 如果样本个数小于2,不够一次买卖操作,直接返回;
* 步骤一:寻找第一次买卖节点,计算本次收益,并与最大收益比较;
* 步骤二:提取剩余样本数据,寻找第二次买卖节点,计算本次收益,与第一次买卖收益累加后,和最大收益比较。
*
* */
public static long calcMaxProfit(int[] p_samples, int startIndex, int endIndex)
{
long maxProfit = 0; //返回值,最大利润;
long firstPartProfitPerloop = 0; //局部变量;第一次操作利润;
long secondPartProfitPerloop = 0;//局部变量;第二次操作利润;
int startSample = 0;//局部变量;买入值;
int endSample = 0;//局部变量;卖出值;

if (endIndex - startIndex >= 2)
{
for (int i = startIndex; i < endIndex; i++) //固定第一次买卖开始样本点
{
startSample = p_samples[i];
for (int j = i+1; j &l
93da
t;= endIndex; j++) //固定第一次买卖结束样本点
{
endSample = p_samples[j];
firstPartProfitPerloop = endSample - startSample;
maxProfit = compareAndSwap(maxProfit, firstPartProfitPerloop);
secondPartProfitPerloop = calcSecondTimeMaxProfit(p_samples, j+1, endIndex); //根据剩余样本数据,计算第二次买卖最大收益
maxProfit = compareAndSwap(maxProfit, firstPartProfitPerloop + secondPartProfitPerloop);
}
}
}

return maxProfit;
}

public static long compareAndSwap(long p_maxProfit, long p_loopProfit)
{
if (p_maxProfit < p_loopProfit)
{
p_maxProfit = p_loopProfit;
}
return p_maxProfit;
}

public static long calcSecondTimeMaxProfit(int[] p_samples, int startIndex, int endIndex)
{
long maxProfit = 0; //返回值,最大利润;
long secondPartProfitPerloop = 0;//局部变量;第二次操作利润;
int startSample = 0;//局部变量;买入值;
int endSample = 0;//局部变量;卖出值;

for (int i = startIndex; i < endIndex; i++) //固定买卖开始样本点
{
startSample = p_samples[i];
for (int j = i+1; j <= endIndex; j++) //固定买卖结束样本点
{
endSample = p_samples[j];
secondPartProfitPerloop = endSample - startSample;
maxProfit = compareAndSwap(maxProfit, secondPartProfitPerloop);
}
}

return maxProfit;
}
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐