C++ 单调栈 勉强过
class Solution {
public:
int maxProfit(vector<int>& prices) {
int len = prices.size();
deque<int> q;
if(len == 1) return 0;
int maxPrice = 0;
for(int i = 0; i < len; i++){
while(!q.empty() && q.back() > prices[i]){
int top = q.back();
q.pop_back();
if(!q.empty()){
maxPrice = max(maxPrice,top-q.front());
}
}
q.push_back(prices[i]);
}
while(!q.empty()){
int top = q.back();
q.pop_back();
if(!q.empty()) maxPrice = max(maxPrice,top-q.front());
}
return maxPrice;
}
};
java 单调栈
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
LinkedList<Integer> list = new LinkedList<Integer>();
int maxPrice = 0;
for(int i = 0; i < len; i++){
while(!list.isEmpty() && list.peekLast() > prices[i]){
int top = list.peekLast();
list.pollLast();
if(!list.isEmpty()) maxPrice = Math.max(maxPrice,top-list.peekFirst());
}
list.offer(prices[i]);
}
while(!list.isEmpty()){
int top = list.pollLast();
if(!list.isEmpty()) maxPrice = Math.max(maxPrice,top-list.peekFirst());
}
return maxPrice;
}
}
C++ O(N) 类似dp
class Solution {
public:
int maxProfit(vector<int>& prices) {
int nowMinBuy = prices[0];
int len = prices.size();
if(len == 1) return 0;
int maxPrice = 0;
for(int i = 1; i < len; i++){
if(prices[i] < nowMinBuy){
nowMinBuy = min(nowMinBuy,prices[i]);
}
if(prices[i] > nowMinBuy) maxPrice = max(maxPrice,prices[i]-nowMinBuy);
}
return maxPrice;
}
};
java 版本
class Solution {
public int maxProfit(int[] prices) {
int len = prices.length;
int maxPrice = 0;
if(len == 1) return 0;
int minBuyPrice = prices[0];
for(int i = 1; i < len; i++){
if(prices[i] < minBuyPrice)
minBuyPrice = Math.min(minBuyPrice,prices[i]);
if(prices[i] > minBuyPrice)
maxPrice = Math.max(maxPrice,prices[i]-minBuyPrice);
}
return maxPrice;
}
}