class Solution { public: int maxProfit(vector<int>& prices) { if(prices.size()==0) return 0; int maxProfit = 0x80000000; vector<int> stack; stack.push_back(prices[0]); for(int i=1;i<prices.size(); ++i) { if(stack.back() < prices[i]) { stack.push_back(prices[i]); } else { maxProfit = max(maxProfit, stack.back()-stack.front()); stack.pop_back(); while(stack.size()>0) { auto tmp = stack.back(); if(tmp >= prices[i]) { stack.pop_back(); } else { break; } } stack.push_back(prices[i]); } } if(stack.size() == 1) { maxProfit = max(maxProfit, 0); } else { maxProfit = max(maxProfit, stack.back()-stack.front()); } return maxProfit; } };
原文地址:https://www.cnblogs.com/randyniu/p/9374752.html
时间: 2024-10-14 06:35:55