买卖股票的最佳时机

题目:

买卖股票的最佳时机

 

描述:假设有一个数组,它的第i个元素是一支给定的股票在第i天的价格。如果你最多只允许完成一次交易(例如,一次买卖股票),设计一个算法来找出最大利润。

 

样例

 

给出一个数组样例 [3,2,3,1,2], 返回 1

 

思考:

我认为买卖股票的最佳时机是以最低的价格买入,以最高的价格抛出。所以是求最大差值(但是这样的理解好像有误区)

 

源码:

方式一:

package day01;

public class maxProfit {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int arr []={3,2,3,1,2};
        System.out.println(maxProfit(arr));

    }
    public static  int maxProfit(int [] prices) {  
                 // write your code here  
                 int i, d,j;  
                 int max = 0;  
                 for(i = 0; i < prices.length-1; i++)
                 for (j=1;j<prices.length;j++){  
                     d = prices[j] - prices[i];  
                     if(d > 0&d>max){  
                         max=d;  
                     }  
                 }  
                return max;  
             }  


}

 

 

方式二:

package day01;

import java.util.Arrays;

public class maxProfit_ {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int arr []={3,2,3,1,2};
        System.out.println(maxProfit(arr));

    }
    public static  int maxProfit(int [] prices) 
    {
        int i=0,max=0;
        Arrays.sort(prices);
        max=prices[prices.length-1]-prices[0];
        return max;
    }

}

 

posted @ 2017-03-08 19:38  Antssss  阅读(124)  评论(0编辑  收藏  举报