Best Time to Buy and Sell Stock
来源:互联网 发布:主机屋空间绑域名 编辑:程序博客网 时间:2024/06/07 01:16
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
遍历过程中记录最大最小值即可,要保证最小值在最大值前面
class Solution {public: int maxProfit(vector<int> &prices) {if(prices.size()<=1) return 0;int max = prices[0],min = prices[0],r_min = prices[0];for(int i=1;i<prices.size();++i){ //当前值比最大的大,变更最大值if(prices[i]>max){max = prices[i];}//当前能取得的最大利润大,更新区间if((prices[i]-r_min)>(max-min)){ min = r_min; max = prices[i];}//更新实际最小值 if(prices[i]< r_min){r_min = prices[i];}} return max - min; }};
0 0
- 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
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- 白沙雜記 勒馬臨門
- Java orb
- 给年轻程序员的建议
- UICollectionViewLayout
- UVA 1412 Fund Management(DP)
- Best Time to Buy and Sell Stock
- Fragment之8_____DialogFragment
- leetcode:pow(x, n)
- Android-SharedPreferences源码学习与最佳实践
- iOS6新特征:UICollectionView高级使用示例之CircleLayout
- ios 屏幕分辨和适配的问题
- 常用CSS缩写规则语法
- [转]Ivshmem实现分析与性能测试
- ASP.NET动态网站开发培训-21.论文管理系统(一、前期准备)