2014年3月26日星期三

Best Time to Buy and Sell Stock

Problem:
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.

Analysis:
Compare the current value with the minimum of the previous values. Keep the maximum profit. The time is O(n).
Solution:
1:  public class Solution {  
2:    public int maxProfit(int[] prices) {  
3:      if(prices==null)  
4:       return 0;  
5:       else  
6:       {  
7:      int min=Integer.MAX_VALUE;  
8:      int profit=0;  
9:      int maxProfit=0;  
10:      for(int i=0;i<prices.length;i++)  
11:      {  
12:        if(prices[i]<=min)  
13:          min=prices[i];  
14:        profit=prices[i]-min;  
15:        if(profit>=maxProfit)  
16:         maxProfit=profit;  
17:      }  
18:      return maxProfit;  
19:       }  
20:    }  
21:  }  

没有评论:

发表评论