标签:
标题: | Best Time to Buy and Sell Stock |
通过率: | 32% |
难度: | 中等 |
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.
leetcode上面题目我感觉好多都没有描述清楚,这题的意思是一支股票每天的价格变换用一个数组保存,如何经过一次的购买和一次的卖出获得最大利润。求最大利润。
这样一解释就瞬间好懂了,这道题就是求最大值和最小值,并且最小值一定要在最大值的前面。
遍历一趟数组即可,便利时,先查看是不是比最小值小,如果小就买入,再看看该值减最小值是不是差值最大,遍历一遍后的差值一定是最大的。
代码如下:
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 if(prices.length==1)return 0; 4 int result=0,low=Integer.MAX_VALUE; 5 for(int i=0;i<prices.length;i++){ 6 if(prices[i]<low)low=prices[i]; 7 if(prices[i]-low>result)result=prices[i]-low; 8 } 9 return result; 10 } 11 }
leetcode------Best Time to Buy and Sell Stock
标签:
原文地址:http://www.cnblogs.com/pkuYang/p/4267209.html