题目:

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.

解题思路:

这道题不难,最简单的解题思路复杂度为O(n2),不过我想应该会超时,这里采用另一种解题方法,复杂度为O(n2)。

采用两个指针i和j,i用来指向所遍历过的元素中最小值,j则用来遍历数组,然后用j指向的值与i指向的值相减,如果差值大于max,则替换max,当j指向的值小于i指向的元素时,将i = j,继续之前的动作。

代码:

#include <iostream>
#include <climits>
#include <vector>
using namespace std; /**
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.empty())
return 0;
int i = 0;
int j = i+1;
int max = 0;
while(j < prices.size())
{
if(prices[j] < prices[i])
{
i = j; }
else
{
int t = prices[j] - prices[i];
if(t > max)
max = t;
}
j++;
}
return max; }
}; int main(void)
{
int arr[] = {2,4,5,1,7,10};
int n = sizeof(arr) / sizeof(arr[0]);
vector<int> stock(arr, arr+n);
Solution solution;
int max = solution.maxProfit(stock);
cout<<max<<endl;
return 0;
}

最新文章

  1. 【POJ 1112】Team Them Up!(二分图染色+DP)
  2. (转)Quartus II和Modelsim的联合仿真(详细)
  3. 在腾讯云上创建您的SQL Cluster(3)
  4. IOS&amp;swift开发常用的网站
  5. Android -- 获取摄像头帧数据解码
  6. C#定时器和事件
  7. pyqt下拉菜单和打开指定的内容(或者exe,doc,ppt,url等内容)
  8. 利用SVNKit进行版本库的树的导出
  9. DNS解析详细过程
  10. js与AMD模块加载
  11. AWSS3异步等待上传成功返回结果
  12. [PHP]session的一些要点
  13. Java基础--对象的序列化
  14. Sort_Buffer_Size 设置对服务器性能的影响
  15. 【C】——回调函数实现泛型算法
  16. 百度地图API —— 制作多途经点的线路导航
  17. 【lua】如何倒序查找字符
  18. BZOJ4823 CQOI2017老C的方块(最小割)
  19. PHP线程安全和非线程安全的区别
  20. 使用加密的squid配合stunnel实现HTTP代理

热门文章

  1. ECMAScript5 Object的新属性方法
  2. Ubuntu 下配置Ganglia监控
  3. Nodejs&#183;进程
  4. iOS-数据持久化-对象归档
  5. javascript_core_07之错误处理、函数作用域
  6. Python - 动手写个ORM
  7. javase基础复习攻略《三》
  8. codeforces——Little Pony and Sort by Shift
  9. java中异常注意问题(发生在多态是的异常问题)
  10. Docker 有什么优势?