给你一个整数数组 prices
,其中 prices[i]
表示某支股票第 i
天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
示例 1:
输入:prices = [7,1,5,3,6,4] 输出:7 解释:在第 2 天(股票价格 = 1)的时候买入,在第 3 天(股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。 随后,在第 4 天(股票价格 = 3)的时候买入,在第 5 天(股票价格 = 6)的时候卖出, 这笔交易所能获得利润 = 6 - 3 = 3 。 总利润为 4 + 3 = 7 。
示例 2:
输入:prices = [1,2,3,4,5] 输出:4 解释:在第 1 天(股票价格 = 1)的时候买入,在第 5 天 (股票价格 = 5)的时候卖出, 这笔交易所能获得利润 = 5 - 1 = 4 。 总利润为 4 。
示例 3:
输入:prices = [7,6,4,3,1] 输出:0 解释:在这种情况下, 交易无法获得正利润,所以不参与交易可以获得最大利润,最大利润为 0 。
提示:
1 <= prices.length <= 3 * 104
0 <= prices[i] <= 104
解法一:
贪心法:
贪心算法的基本思路是从问题的某一个初始解出发一步一步地进行,根据某个优化测度,每一步都要确保能获得局部最优解。
解题思路:
买卖股票的策略:
单独交易日:设今日的股票价钱为p1,明天的股票价钱为p2,假设第二天卖出,则收入或亏损为p2-p1
连续上涨交易日:
设此上涨交易日股票价格分别为p1,p2,p3,p4......pn,则pn-p1;等价于每天都买卖,即pn-p1=(p2-p1)+(p3-p2)+......+(pn-pn-1)
连续下降交易日:
不买卖,否则会亏钱。
算法流程:
遍历整个股票的交易价格,如果后一天的价格比前一天的多,那就前一天买,后一天卖,否则,不进行买卖交易。
int maxProfit(int* prices, int pricesSize){
int i;
int total=0;
for(i=0;i+1<pricesSize;i++)
{
if(prices[i]<prices[i+1])
{
total=total+prices[i+1]-prices[i];
}
}
return total;
}
解法二:
类动态规划
递归法:
int maxProfit(int* prices, int pricesSize){
if(pricesSize<=1)
{
return 0;
}
int max=0;
int profit;
//max(//1.假设最后一天不卖
//[7,1,5,3,6,4]<=>[7,1,5,3,6]<=>maxProfit(prices,5)
profit=maxProfit(prices,pricesSize-1);
if(max<profit)
{
max=profit;
}
//2.假设最后一天卖
//max(
// [7,1,5,3,6]+(6,4)<=>maxProfit(prices,5)+prices[5]-prices[4]
// [7,1,5,3]+(3,4)<=>maxProfit(prices,4)+prices[5]-prices[3]
// [7,1,5]+(5,4)<=>maxProfit(prices,3)+prices[5]-prices[2]
// [7,1]+(1,4)<=>maxProfit(prices,2)+prices[5]-prices[1]
// [7]+(7,4)<=>maxProfit(prices,1)+prices[5]-prices[0]
//)
for(int i=1;i<=pricesSize-1;i++)
{
profit=maxProfit(prices,i)+prices[pricesSize-1]-prices[i-1];
if(max<profit)
{
max=profit;
}
}
return max;
//)
}
非递归法:
int maxProfit(int* prices, int pricesSize){
if(pricesSize<=1)
{
return 0;
}
int profits[pricesSize+1];
profits[1]=0;
for(int k=2;k<=pricesSize;k++){
int max=0;
int porfit;
//max(//1.假设最后一天不卖
//[7,1,5,3,6,4]<=>[7,1,5,3,6]<=>maxProfit(prices,5)
porfit=profits[k-1];
if(max<porfit)
{
max=porfit;
}
//2.假设最后一天卖
//max(
// [7,1,5,3,6]+(6,4)<=>maxProfit(prices,5)+prices[5]-prices[4]
// [7,1,5,3]+(3,4)<=>maxProfit(prices,4)+prices[5]-prices[3]
// [7,1,5]+(5,4)<=>maxProfit(prices,3)+prices[5]-prices[2]
// [7,1]+(1,4)<=>maxProfit(prices,2)+prices[5]-prices[1]
// [7]+(7,4)<=>maxProfit(prices,1)+prices[5]-prices[0]
//)
for(int i=1;i<=k-1;i++)
{
porfit=profits[i]+prices[k-1]-prices[i-1];
if(max<porfit)
{
max=porfit;
}
}
profits[k]=max;
}
//)
return profits[pricesSize];
}