Best Time to Buy and Sell Stock
2013-10-17 02:33
267 查看
Objective:
Find out the lowest point to buy-in and find out the a following hightest point to sell-out. And the maximal profit is equivalent to the max difference between the highest point and lowest point.
Before solving this problem, suggest referring to the "maximum subarray" first. Then you will get an idea how to set the pointer and how to store the "buy" and "sell" variables.
Find out the lowest point to buy-in and find out the a following hightest point to sell-out. And the maximal profit is equivalent to the max difference between the highest point and lowest point.
Before solving this problem, suggest referring to the "maximum subarray" first. Then you will get an idea how to set the pointer and how to store the "buy" and "sell" variables.
class Solution { public: int maxProfit(vector<int> &prices) { // Note: The Solution object is instantiated only once and is reused by each test case. if (prices.empty()) return 0; int cur = 0; // the pointer int buy = 0; // date to buy int sell = 0; // day to sell int maxProf = 0; // the maximum profit for(int i=1;i<prices.size();i++) { if(prices[i]<prices[cur]) cur = i; else if(prices[i]>prices[cur] && prices[i]-prices[cur]>maxProf) { buy = cur; sell = i; maxProf = prices[i]-prices[cur]; } } return maxProf; } };
相关文章推荐
- 函数1(四)
- nodejs服务
- 【学习】linux shell 编程
- RHEL6.4更改为CentOS6.4的yum源
- 单链表操作大全
- 在 php 中通过 CURL 上传文件
- 一句话经典总结红黑树插入
- 小流涓涓成江海,拙技点点构平台——多线程开发
- 英文面试自我介绍
- RHEL6安装图形界面
- 白话经典算法系列之——快速排序
- java System类
- 【MZ】ZOJ 3494 BCD Code AC自动机+数位DP
- Permutations II
- PID 在机器人self balance中应用
- SQL Server 索引结构及其使用
- SQL语句――COUNT
- SQL语句――创建表,添加记录
- IOS中的结构体保存到数组与读取
- 白话经典算法系列之——希尔排序的实现