所有的LeetCode题解索引,可以看这篇文章——【算法和数据结构】LeetCode题解。
??思路分析:股票要想盈利,必须低买高卖。在第N天买入,然后在第M天卖出,所获的利润是price[M]-price[N],而这个利润公式可以分解成:
p
r
i
c
e
[
M
]
?
p
r
i
c
e
[
N
]
=
(
p
r
i
c
e
[
M
]
?
p
r
i
c
e
[
M
?
1
]
)
+
(
p
r
i
c
e
[
M
?
1
]
?
p
r
i
c
e
[
M
?
2
]
)
+
.
.
.
+
(
p
r
i
c
e
[
N
+
2
]
?
p
r
i
c
e
[
N
+
1
]
)
+
(
p
r
i
c
e
[
N
+
1
]
?
p
r
i
c
e
[
N
]
)
\begin{align*} price[M]-price[N]&=(price[M]-price[M-1])+(price[M-1]-price[M-2])+... \\ &+(price[N+2]-price[N+1])+(price[N+1]-price[N]) \end{align*}
price[M]?price[N]?=(price[M]?price[M?1])+(price[M?1]?price[M?2])+...+(price[N+2]?price[N+1])+(price[N+1]?price[N])?
??即N买M卖的利润可以由M和N天中间的股票价格的差值得到,因此我们去计算price数组后一个元素与前一个元素的差值。取差值数组的和就是最终所得最大利润。
??程序如下:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int result = 0;
for (int i = 0; i < prices.size() - 1; i++) {
result += max(prices[i + 1] - prices[i], 0);
}
return result;
}
};
复杂度分析:
# include <iostream>
# include <vector>
# include <algorithm>
using namespace std;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int result = 0;
for (int i = 0; i < prices.size() - 1; i++) {
result += max(prices[i + 1] - prices[i], 0);
}
return result;
}
};
int main() {
vector<int> prices = { 7,1,5,3,6,4 };
Solution s1;
int result = s1.maxProfit(prices);
cout << result << endl;
system("pause");
return 0;
}
end