Best Time to Buy and Sell Stock
来源:互联网 发布:mac pr防抖cc2017 编辑:程序博客网 时间:2024/04/29 13:43
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.
思路:题目的意思是求买入一次股票然后再卖出该股票的最大收益,意思就是求prices数组最大的值与最小值的差,但是最大值的索引肯定要在最小值索引前面。对于这种类型的题目,要想到用一个值,比如res来保存当前的最大利益,在遍历的过程中不断更新res的值,遍历完数组最大利益res也就确定了。那么怎么更新当前最大利益的的值呢?
要更新当前的最大利益res的值,就要先保存遍历到当前出现的数组中出现的最小的值currentMin,用当前值减去currentMin的值再与前一次保存的res相比较,比较大的就为当前的最大利润。
public class Solution { public int maxProfit(int[] prices) { int res=0; if(prices.length==0) return 0; int currentMin=prices[0]; for(int i=1;i<prices.length;i++) { if(prices[i]<prices[i-1]) { currentMin=Math.min(currentMin,prices[i]); } else res=Math.max(res,prices[i]-currentMin); } return res; }}
0 0
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time To Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- Best Time to Buy and Sell Stock
- 编程思想之多线程与多进程(1)——以操作系统的角度述说线程与进程
- window下 运行javac,java,javap(编译)
- bzoj1036树的统计Count
- 剑指offer-第二章-基础篇
- 用java开发的一个简单的记事本程序
- Best Time to Buy and Sell Stock
- 让左侧栏中的tableView点击以push方式弹出,并且拥有手势返回
- mysql基本语法大全
- linux 端口占用
- Java基础—泛型
- U盘安装优麒麟(ubuntukylin)系统方法
- java简单的字符串大小比较——compareTo()方法
- 图片文字缓存(下)图片缓存
- 名言哲理-让心灵找到归属