码迷,mamicode.com
首页 > 其他好文 > 详细

121-Best Time to Buy and Sell Stock

时间:2015-04-13 14:36:03      阅读:100      评论:0      收藏:0      [点我收藏+]

标签:

题目:

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;
    }
}

  

 

121-Best Time to Buy and Sell Stock

标签:

原文地址:http://www.cnblogs.com/hwu2014/p/4422009.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!