LeetCode-Best Time to Buy and Sell Stock
来源:互联网 发布:mhx配装器 java怎么用 编辑:程序博客网 时间:2024/06/03 14:56
原题描述:
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
即:在一个数组中,第i
个元素代表的是第i
天的stock价格,要求在某天i
买入,在某天j
天卖出,使得收益最大。最多交易一次,可以不进行交易,即收益为0.
分析:
收益 = 售出时价格 - 买进时价格
如果现在已知结果是在i
天买入,在j
天卖出,这些天stock的价格是:
收益为:i
天到第j
天的收益之和,其中
prices数组转换成difference数组,求difference数组的最大子array和,即寻找最大子数列
最大子数列问题:
有数组
问题分析:
对于数组
- 如果
Bk+1 包含k+1 以前的元素,那么Bk+1=ak+1∪(含k的最大和) ,即Bk+1=ak+1∪Bk - 如果
Bk+1 不包含k+1 以前的元素,那么Bk+1=ak+1
综上所述,有Bk+1=max(ak+1,ak+1∪Bk)
此解法称为 Kadane’s Algorithm
问题要求的最大子序列和,可以转换成求
curmax=0maxsofar=0for i in range(len(A)): curmax=max(A[i],A[i]+curmax) maxsofar=max(curmax,maxsofar)#maxsofar就是最大子序列和
回到本题售价中,则只需要将prices数组转换成差价数组之后,使用Kadane’s Algorithm即可解决!
阅读全文
1 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
- 在执行目录下找文件
- logback系统异常日志写入文件
- 【美团外卖】广告算法 高级研发工程师/技术专家
- eclipse 项目中嵌入jetty
- SSH 访问内网
- LeetCode-Best Time to Buy and Sell Stock
- img标签,图片占位
- Http常见状态码
- springboot整合mongodb
- Vue2.0实现调用摄像头进行拍照功能以及图片上传功能引用exif.js
- 使用kittle自带的“START”实现不同数据库的数据复制、迁移的操作的计划任务
- SourceTree进行开发Git项目图解
- 百度2017年计算机视觉笔试题---续
- spring-boot项目按照平常的web项目一样发布到tomcat容器下