【LeetCode】121.Best Time to Buy and Sell Stock解题报告
来源:互联网 发布:源码资本海外招聘 编辑:程序博客网 时间:2024/06/05 09:22
【LeetCode】121.Best Time to Buy and Sell Stock解题报告
tags: Array
题目地址:https://leetcode.com/problems/best-time-to-buy-and-sell-stock/#/description
题目描述:
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.
Example1:
Input: [7, 1, 5, 3, 6, 4] Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example2:
Input: [7, 6, 4, 3, 1] Output: 0
In this case, no transaction is done, i.e. max profit = 0.
题意:从前到后,找两个递增的数,求最大差值。
Solution:
public class Solution { public int maxProfit(int[] prices) { if(prices.length==0) return 0; int low=prices[0]; int ans=0; for(int i=1;i<prices.length;i++){ if(prices[i]<low){ low=prices[i]; }else if(prices[i]-low>ans){ ans=prices[i]-low; } } return ans; }}
Date:2017年6月23日
阅读全文
0 0
- LeetCode-Best Time to Buy and Sell Stock-解题报告
- 【LeetCode】Best Time to Buy and Sell Stock 解题报告
- [leetcode] 121. Best Time to Buy and Sell Stock 解题报告
- Leetcode 121. Best Time to Buy and Sell Stock 股票买卖 解题报告
- [Leetcode] 121. Best Time to Buy and Sell Stock 解题报告
- [leetcode]解题报告121. Best Time to Buy and Sell Stock
- 【LeetCode】121.Best Time to Buy and Sell Stock解题报告
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- 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 IV -解题报告
- 【LeetCode】 Best Time to Buy and Sell Stock I II III IV 解题报告
- [leetcode] 123. Best Time to Buy and Sell Stock III 解题报告
- [leetcode] 122. Best Time to Buy and Sell Stock II 解题报告
- [leetcode] 309. Best Time to Buy and Sell Stock with Cooldown 解题报告
- [leetcode] 188. Best Time to Buy and Sell Stock IV 解题报告
- leetcode 309. Best Time to Buy and Sell Stock with Cooldown 解题报告
- LeetCode 122. Best Time to Buy and Sell Stock II 解题报告
- cocos2d-x 帧循环
- ant打包项目,部署
- CDH5.11添加kafka服务及其初始启动OutOfMemoryError失败解决
- angularJs-工具方法2
- 移动平台资源路径问题
- 【LeetCode】121.Best Time to Buy and Sell Stock解题报告
- oracle监听器安全
- Android提供了短信群发的机制
- 书籍-Java性能调优指南
- python的selenium不管项目模块迁移哪个项目文件目录下,都用这句代码解决
- 创建bootstrap的表格(含日期控件)
- RTSP协议学习笔记
- phpstorm连接sftp报错:session is down
- android实现正方形的ImageView、Layout等(即高度适应宽度或者宽度适应高度)