买卖股票的最佳时机
给定一个数组prices,其中prices[i] 是一支给定股票第i天的价格
设计一个算法来计算你所能获取的最大利润
1. 只能买卖一次
思路:从1开始到最后,记录当前位置前面的最小值,获取当下卖出的盈利,最终比较得到最大盈利
int getMaxProfit(int prices[],int len)
{
if(len <= 1)
{
return 0;
}
int buyInMin = prices[0];
int sellMax = 0;
for(int i = 1;i < len;i++)
{
if(prices[i] - buyInMin > sellMax)
{
sellMax = prices[i] - buyInMin;
}
if(prices[i] < buyInMin)
{
buyInMin = prices[i];
}
}
sellMax = sellMax > 0 ? sellMax:0;
qDebug() << "\nmax profit: " << sellMax << endl;
return sellMax;
}
2. 可买卖多次,多次买卖一只股票,但不能同时参与多笔交易
解法一:
/*
* 买卖股票的最佳时机 :可买卖多次(多次买卖一只股票,但不能同时参与多笔交易),求最大盈利
*思路: 贪心算法1
* 今天持有股票:如果明天不涨,继续持有不卖;如果明天跌,今天卖出,不持有
* 今天不持有股票:如果明天涨,今天买入;如果明天跌,继续持有
*/
int getMaxProfit1(int prices[],int len)
{
if(len <= 1)
{
return 0;
}
int totalProfit = 0; //总盈利
int curStatus = 0; // 0 不持有股票,1 持有股票
for(int i = 0;i < len - 1;i++)
{
if(curStatus == 0 && prices[i] < prices[i+1]) //最后一天不能买入
{
curStatus = 1; //买入
totalProfit -= prices[i];
}
else if(curStatus == 1 && prices[i] > prices[i+1]) //第一天不能卖出
{
curStatus = 0; //卖出
totalProfit += prices[i];
}
}
if(curStatus == 1)
{
curStatus = 0; //卖出
totalProfit += prices[len - 1];
}
qDebug() << "\nmax profit: " << totalProfit << endl;
return totalProfit;
}
解法二:
/*
* 买卖股票的最佳时机 :可买卖多次(多次买卖一只股票,但不能同时参与多笔交易),求最大盈利
*思路: 贪心算法2
* 两两上升盈利的总和
*
*/
int getMaxProfit2(int prices[],int len)
{
if(len <= 1)
{
return 0;
}
int totalProfit = 0;
for(int i = 0; i< len - 1;i++)
{
if(prices[i+1] > prices[i])
{
int v = prices[i+1] - prices[i];
totalProfit += v;
}
}
qDebug() << "\nmax profit: " << totalProfit << endl;
return totalProfit;
}