LeetCode:Best Time to Buy and Sell Stock
来源:互联网 发布:js正则表达式数字范围 编辑:程序博客网 时间:2024/05/16 09:22
problem:
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]Output: 5max. difference = 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: 0In this case, no transaction is done, i.e. max profit = 0.这个问题实际上就是给你一串数字,让你找出这组数字中任意两个数字间最大的差值。
因为自己算法渣,当时看到这个问题的第一个想法就是,采用O(N^2)的方法,遍历两次数组,依次比较任意两个数字之间的差值,记录下最大的值。但是这种方法在LeetCode上是超时了,因为复杂度太大了。可能只遍历一边数组就可以解决这个问题。
基于这种想法,给出如下思路,我们在遍历数组的时候,我们声明两个变量,一个min1,max1,分别记录数组中最下的数字和两个数字之间的最大差值
给出代码,
class Solution {public: int maxProfit(vector<int>& prices) { if(prices.size()==0) return 0; int max1=0; int min1=INT_MAX; for(int i=0;i<prices.size();i++) { min1=min(min1,prices[i]); max1=max(max1,prices[i]-min1); } return max1; }};
0 0
- 【LeetCode】Best Time to Buy and Sell Stock & Best Time to Buy and Sell Stock
- [LeetCode] [LeetCode]Best Time to Buy and Sell Stock
- 【LeetCode with Python】 Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock
- [LeetCode]Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock
- LeetCode Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- Leetcode: Best time to buy and sell a stock I
- Leetcode: Best Time to Buy and Sell Stock II
- LeetCode Best Time to Buy and Sell Stock III
- [Leetcode] Best Time to Buy and Sell Stock
- [Leetcode] Best Time to Buy and Sell Stock II
- [Leetcode] Best Time to Buy and Sell Stock III
- LeetCode : Best Time to Buy and Sell Stock II
- [leetcode] Best Time to Buy and Sell Stock
- leetcode 16: Best Time to Buy and Sell Stock III
- LeetCode Best Time to Buy and Sell Stock
- QDUOJ 37 帅气的HYC的珍珠(树状数组)
- 登录错误多次密码锁定账户一定时间之数据库建表参考
- linux 中shell编程中的test用法
- 马拉松式学习与技术人员的成长性
- hibernate文件配置出现Repeated column in mapping for entity的Mapping异常处理
- LeetCode:Best Time to Buy and Sell Stock
- Codeforces Round #406 (Div. 1) C. Till I Collapse(主席树)
- Java拾遗2:文件传输基础——Java IO流
- 《30天自制操作系统》学习笔记Day1
- Immutable bitmap crash error
- Android搭建HTTP服务,作为MediaPlayer的播放源来播放音频
- 2017湖南多校第五场-A(1043): Biorhythms
- 正则匹配之匹配网页img
- java xml dom4j 创建 修改 解析