你的位置:首页 > 软件开发 > Java > [LeetCode] Best Time to Buy and Sell Stock

[LeetCode] Best Time to Buy and Sell Stock

发布时间:2015-08-17 13:00:34
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 ...

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.

 

     这道题就不仅仅只是算法题了,我们还要考虑到生活中的常识。

     比如这个是Buy and Sell,就说明我们必须是先Buy然后再Sell。

     比如第五天价格最低,第三天价格最高,我们肯定不能第五天买了然后穿越回去第三天卖出去啊。所以loop的时候要考虑到这些因素。

     代码如下。~

public class Solution {  public int maxProfit(int[] prices) {    //special case    if(prices==null||prices.length<2){      return 0;    }    int min=prices[0];    int profit=0;    for(int i=0;i<prices.length;i++){      if(profit<(prices[i]-min)){        profit=prices[i]-min;      }else if(prices[i]<min){        min=prices[i];      }    }    return profit;  }}

原标题:[LeetCode] Best Time to Buy and Sell Stock

关键词:

*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。

可能感兴趣文章

我的浏览记录