【Best Time to Buy and Sell Stock】cpp
2015-05-30 08:59
405 查看
题目:
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.
代码:
tips:
Greedy
核心在于维护两个变量:
min_price: 算上当前元素的最小值
max_profit:算上当前元素的最大利润
走完所有元素,可以获得max_profit
================================================
第二次过这道题,犹豫了一下才想起来思路。
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()==0) return 0; int min_price = prices[0], max_profit = 0; for ( size_t i = 0; i < prices.size(); ++i ) { min_price = std::min(min_price, prices[i]); max_profit = std::max(max_profit, prices[i]-min_price); } return max_profit; } };
tips:
Greedy
核心在于维护两个变量:
min_price: 算上当前元素的最小值
max_profit:算上当前元素的最大利润
走完所有元素,可以获得max_profit
================================================
第二次过这道题,犹豫了一下才想起来思路。
class Solution { public: int maxProfit(vector<int>& prices) { int globalProfit = 0; if ( prices.empty() ) return globalProfit; int minPrice = prices[0]; for ( int i=1; i<prices.size(); ++i ) { minPrice = min(minPrice, prices[i]); globalProfit = max(globalProfit, prices[i]-minPrice); } return globalProfit; } };
相关文章推荐
- 标准c++库和stl库,boost库,qt库的总结(一)
- 《C++编程思想》 第一章 对象的演化
- C++对象模型之默认构造函数的构造操作
- c++运算符重载
- c++语言实现装饰模式代码示例
- c++位移计算
- switch case语句块default的认识
- 在Android C/C++层添加LOG调试(LOGI\LOGD\LOGE...)输出支持
- c/c++与as3中的逗号表达式
- 关于C++类成员函数的重载、覆盖、隐藏与virtual关键字
- 杭电里面水题的RPG问题
- 深入理解C++的动态绑定和静态绑定
- C++作业第四章实验4
- c++14现行标准
- 由C/C++编译的程序占用的内存分类
- 【C++】基于特征向量的KNN分类算法
- 对C++中迭代器的分类的认识
- C++11新特性
- c++重载运算符@
- 【学习笔记】【C语言】常量