美文网首页
Best Time to Buy and Sell Stock

Best Time to Buy and Sell Stock

作者: Leonlong | 来源:发表于2017-01-06 06:26 被阅读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.
ExampleGiven array [3,2,3,1,2], return 1

比较经典的题目了,由于只能做一次交易,所以设定两个变量,一个不断追踪最大的profit,一个不断更新最小值

public class Solution {
    /**
     * @param prices: Given an integer array
     * @return: Maximum profit
     */
    public int maxProfit(int[] prices) {
        // write your code here
        if (prices == null || prices.length ==0) {
            return 0;
        }
        
        int maxProfit = 0, min = prices[0];
        
        for (int i=1; i < prices.length; i++) {
            int profit = prices[i]-min;
            maxProfit = Math.max(profit, maxProfit);
            min = Math.min(min, prices[i]);
        }
        return maxProfit;
    }
}

相关文章

网友评论

      本文标题:Best Time to Buy and Sell Stock

      本文链接:https://www.haomeiwen.com/subject/restbttx.html