题目描述
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
------------------------------------------------------------------------------------------------------------
求解思路:
1,先找到第一个较小买入价格,然后找到一个较大卖出价格,记录较大利益;
2,(1)当较大价格后一天的价格不小于上次较小价格时,递归求后半部分的较大利益,最终取最大
(2)否则,将后一天价格修改为较小后再同上递归求解。
代码实现:
简洁解答:语言:C++
运行时间: <1 ms
占用内存:8552K
状态:答案正确
class
Solution {
public
:
int
maxProfit(vector<
int
> &prices) {
if
(prices.size() <=
1
)
{
return
0
;
}
int
max =
0
;
for
(
int
i =
0
; i < prices.size() -
1
; i++)
{
for
(
int
j = i +
1
; j < prices.size(); j++)
{
int
pro = prices[j] - prices[i];
max = pro > max ? pro : max;
}
}
return
max;
}
};
|