博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeeTCode 121 Best Time to Buy and Sell Stock 股票买卖最佳时间
阅读量:7252 次
发布时间:2019-06-29

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

Desciption

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: 5

Explanation: 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: 0

Explanation: In this case, no transaction is done, i.e. max profit = 0.

思考

最直观的方式是检查所有可能的买卖组合。但是注意卖出一定是在买入之后。假设买入价为 a,卖出价为 b,b-a 需要取一个最大值,既然卖出在后,买入在前,那么数组中的一个元素,不可能同时是 a 和 b ,且 a 一定是位于 b 之前的所有数中最小的那个,因此在一次遍历中,我们对每个元素进行检查,先看它是否是 a(当前最小的数), 如果不是 a,那么再检查它是否是 b(当前令 b - a 最大的数)。遍历完成后,就可以得到 b - a 的最大值了。

func maxProfit(prices []int) int {	minprice := math.MaxInt64	maxprofit := 0	for _, p := range prices {		if p < minprice {			minprice = p		} else if p-minprice > maxprofit {			maxprofit = p - minprice		}	}	return maxprofit}复制代码

tags: 民间算法 数组 遍历

转载于:https://juejin.im/post/5cdbd15bf265da038145fcdb

你可能感兴趣的文章
python实战===itchat
查看>>
[mybatis]Example的用法
查看>>
dSYM文件
查看>>
3D跑酷遇到的问题
查看>>
putty 、xshell的使用 和 putty 、xshell、 shell 间免密登陆
查看>>
项目管理之怒目相争,外行能不能领导内行做软件开发?
查看>>
扬帆起航,再踏征程(四)
查看>>
Objective-C基础笔记(2)@property和@synthesize
查看>>
Android系统开发(1)——GCC编译器的编译和安装过程
查看>>
详解Python模块导入方法
查看>>
mysql一些权限相关操作,数据库可以远程连接或者说用IP地址可以访问
查看>>
关于c#(vs)dategridview控件继承不能修改的问题
查看>>
JAVA通过使用sort方法排序
查看>>
跨域CORS 、第二章
查看>>
一秒去除Win7快捷方式箭头
查看>>
Linux上Simplescalar/ARM的安装和运行文档
查看>>
中断是CPU的机制
查看>>
DoD and DoR
查看>>
Python学习笔记【第二篇】:运算符、比较、关系运算符
查看>>
golang 资源
查看>>