Num 121 买卖股票的最佳时期 Best Time to Buy and Sell Stock
class Solution { public: int maxProfit(vector<int>& prices) { int len=prices.capacity(); if(prices.capacity()==0) return 0; int minn=prices[0]; int maxn=prices[0]; int ans=0; for(int i=0;i<=len-2;i++) { maxn=prices[i]; minn=prices[i]; for(int j=i+1;j<=len-1;j++) { if(prices[j]>maxn) maxn=prices[j]; } ans=max(ans,maxn-minn); } return ans; } };
Num 122 买卖股票的最佳时期 || Best Time to Buy and Sell Stock ||
先上一个正确但是TLE的方法。。。
class Solution { public: int maxProfit(vector<int>& prices) { int ans[50000]; int len=prices.capacity(); if(len==0||len==1) return 0; memset(ans,0,sizeof(ans)); if(len==2) return max(0,prices[1]-prices[0]); ans[len-2]=max(0,(int)(prices[len-1]-prices[len-2])); for(int j=len-3;j>=0;j--) { for(int i=1;i<len-1-j;i++) { ans[j]=max(ans[j],max(ans[j+i],ans[j+i]+(int)(prices[j+i]-prices[j]))); } } return ans[0]; } };
默认里面带的max函数只能处理两个
另外这道题是贪心,刚开始重复计算tle了
class Solution { public: int maxProfit(vector<int>& prices) { int ans=0; int len=prices.capacity(); for(int i=0;i<len-1;i++) ans=ans+max(0,prices[i+1]-prices[i]); return ans; } };