题目描述:
给定一个最佳数组prices,其中prices[i]表示股票第i天的价格。
在每一天,你可能会决定购买和出售股票。你在任何时候最多只能持有一股股票。你也可以购买它,然后在同一天出售。
你需要返回你所能获得的最大利润。
示例:
输入: prices = {7,1,5,3,4,6,1}
输出: 7
解释:第二天买入,,第三天卖出,获利4,第四天买入,第六天卖出,获利3,一共获得利润为7.
分析:我们需要在股价低的时候买入股票,股价高的时候卖出。
因此购买时间可这样定义:若前一天prices小于后一天的prices那么选择购买股票
卖出时间这样规定 : 若明天prices下降,那么今天将股票卖出
说到底,我们要考虑相邻两天的股票价格,后一天的价格大于前一天的股票价格,那么我们在进行买入卖出操作将会获利,在不考虑交易次数的情况下,这样一定会获得最大利润
int maxProfit(int* prices, int pricesSize)
{
assert(prices != NULL);
int* p = prices;
int len = pricesSize;
int profit = 0;
for (int i = 0; i < len-1; i++)
{
if (p[i] < p[i + 1])
{
profit += p[i + 1] - p[i];
}
}
return profit;
}
题目来源于Leetcode