Best Time to Buy and Sell Stock (Medium)

Description

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.

Analysis

只有交易一次,求最大收益值。维护当前最小值,不断更新最大收益

My Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//C++
class Solution {
public:
int maxProfit(vector<int> &prices) {
int len = prices.size();
if(len==0)
return 0;
int ans = 0 , minx = prices[0];
for(int i = 1;i<len;i++){
if(prices[i]>minx){
ans = max(ans,prices[i]-minx);
}
else{
minx = prices[i];
}
}
return ans;
}
};