Leetcode 刷题: Best Time to buy and sell stock

来源:互联网 发布:mac地址怎么查 编辑:程序博客网 时间:2024/05/12 12:58

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.

Subscribe to see which companies asked this question

Show Tags
Show Similar Problems










public class Solution {
    public int maxProfit(int[] prices) {
        //make decision for extreme conditions
        if(prices.length==0 || prices == null)
        return 0;
        
        int profit=0, min=Integer.MAX_VALUE;
        for(int i:prices){
            min=(i < min)?i:min;
            profit= (i-min)>profit ?(i-min):profit;
            
        }
        return profit;
        
    }
}


0 0
原创粉丝点击