博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode121—Best Time to Buy and Sell Stock
阅读量:4588 次
发布时间:2019-06-09

本文共 1008 字,大约阅读时间需要 3 分钟。

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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Note that you cannot sell a stock before you buy one.

Example 1:

Input: [7,1,5,3,6,4]Output: 5Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.   Not 7-1 = 6, as selling price needs to be larger than buying price.

Example 2:

Input: [7,6,4,3,1]Output: 0Explanation: In this case, no transaction is done, i.e. max profit = 0.
想法:找到价格差最大即可
class Solution {public:    int maxProfit(vector
& prices) { int maxPrices = 0;; int minPrices = INT_MAX; for(int i = 0 ; i < prices.size() ; i++){ minPrices = min(minPrices,prices[i]); maxPrices = max(maxPrices,prices[i]-minPrices); } return maxPrices; }};

转载于:https://www.cnblogs.com/tingweichen/p/9968523.html

你可能感兴趣的文章
Android弹出Toast工具类总结
查看>>
吴恩达机器学习笔记(十) —— 推荐系统
查看>>
Linux下Ant安装与配置
查看>>
实验二 用机器指令和汇编指令编程
查看>>
大数据系列之kafka监控kafkaoffsetmonitor安装
查看>>
常用正则表达式
查看>>
Java基础知识
查看>>
Identity Server4学习系列三
查看>>
我的一些学习资源
查看>>
第二届i春秋挖洞大赛的一些感想
查看>>
YAML 语言教程
查看>>
ios开发之C语言基础
查看>>
Cocos Console命令总结
查看>>
网页回到顶部 GoTop 按钮自动隐藏
查看>>
循环语句
查看>>
数据结构与算法(7) -- 二叉查找树
查看>>
【校招面试 之 C/C++】第7题 C++构造函数不能是虚函数的原因
查看>>
Mysql事务及锁
查看>>
TNS-01251: Cannot set trace/log directory under ADR
查看>>
最后一面《HR面》------十大经典提问
查看>>