首页 > 其他 > 详细

121-Best Time to Buy and Sell Stock

时间:2015-04-13 14:33:39      阅读:285      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!