121-Best Time to Buy and Sell Stock

题目:

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.

思路:

1.目标是求数组中的某两个值的差(最大差值),前提是大的数在小的数后面

2.循环遍历数组,设置一个当前最小值min(初始为Integer.MAX_VALUE)和一个最大差值max(初始化为0)

   每次更新min,并更新max(当前元素值-min)

public class Solution {
    public int maxProfit(int[] prices) {
         int len=prices.length;     //数组长度
         int max=0;                    //最大差值
         int min=Integer.MAX_VALUE;              //当前最小值
         for(int i=0;i<len;i++) {
             if(prices[i]<min)
                  min=prices[i];
             if(prices[i]-min>max)
                  max=prices[i]-min;
         }
         return max;
    }
}

  

 

posted @ 2015-04-13 13:51  hwu_harry  阅读(100)  评论(0编辑  收藏  举报