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