121. Best Time to Buy and Sell Stock(只允许一次交易)
来源:互联网 发布:提供rs485数据电缆价格 编辑:程序博客网 时间:2024/04/29 15:17
算法一(动态规划):
class Solution {public: int maxProfit(vector<int>& prices) { if (prices.size() < 2) return 0; int maxProfit = 0; int curMin = prices[0]; for (int i = 1; i < prices.size(); i++) { curMin = curMin<prices[i]?curMin:prices[i]; maxProfit = maxProfit>(prices[i] - curMin)?maxProfit:(prices[i] - curMin); } return maxProfit; }};
算法二(暴力破解):
代码如下:
class Solution {public: int maxP(vector<int>& prices,int left,int right){ if(left==right)return 0; int i=left,j=left,max,min; max=min=prices[left]; for(int k=left;k<=right;++k){ if(min>prices[k]){min=prices[k];i=k;} if(max<prices[k]){max=prices[k];j=k;} } if(i<=j)return max-min; else{ int val1=maxP(prices,left,j); int val2=maxP(prices,j+1,i-1); int val3=maxP(prices,i,right); int temp=val1>val2?val1:val2; return (temp>val3?temp:val3); } } int maxProfit(vector<int>& prices) { if(prices.size()==0)return 0; return maxP(prices,0,prices.size()-1); }};
0 0
- 121. Best Time to Buy and Sell Stock(只允许一次交易)
- LeetCode 121. Best Time to Buy and Sell Stock--股票买入后再卖出,求最大收益,最多交易一次
- LeetCode WIith JS || 121. Best Time to Buy and Sell Stock[求股票的最佳收益,只能交易一次]
- leetcode 121. Best Time to Buy and Sell Stock-股市交易
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- 2012北邮计算机考研复试上机题解
- OpenCV2.4.10之samples_cpp_tutorial-code_learn-----ImgTrans(Laplace边缘检测和Sobel边缘检测,图像重映射)
- hdu 5667 Sequence(BC——矩阵快速幂)
- colorAccent,colorPrimary,colorPrimaryDark……来这里你就明白了
- ZooKeeper介绍、分析、理解
- 121. Best Time to Buy and Sell Stock(只允许一次交易)
- ldpack工作日记-2016/4/27
- 剑指offer:丑数
- Android网络框架 - Retrofit基本使用
- LeetCode *** 345. Reverse Vowels of a String
- Qt 设置QLabe中字体的颜色
- 西电OJ - 1035 数独
- Android Framework系统服务详解
- 案例分析7