社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
题目链接:Leetcode121
思路:
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n == 0) return 0;
int stk[n], top = -1;
int ans = 0;
for (int i = 0; i < n; i++) {
while (top!=-1 && stk[top]>=prices[i]) top--; //模拟一个单调栈
stk[++top]=prices[i];
ans=max(ans, stk[top]-stk[0]);
}
return ans;
}
};
class Solution {
public:
int maxProfit(vector<int>& prices) {
int n = prices.size();
if (n == 0) return 0;
int bef; //int dp[n];
int ans = 0;
bef=prices[0]; //dp[0]=prices[0]; //初试状态
for (int i = 1; i < n; i++) {
/*
dp[i]=min(dp[i-1], prices[i]);
ans=max(ans, prices[i]-dp[i-1]); //在正数内所以不存在溢出的情况,因为负数比正数多一位
*/
ans=max(ans, prices[i]-bef);
bef=min(bef, prices[i]);
}
return ans;
}
};
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!