Best Time to Buy and Sell Stock

来源:互联网 发布:dns劫持后的域名来路 编辑:程序博客网 时间:2024/04/26 01:37
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.


Solution:
public class Solution {
    public int maxProfit(int[] prices) {
        if(prices==null||prices.length==0)
             return 0;
        int cost = prices[0];
        int profit = 0;
        
        for(int i=0;i<prices.length;i++)
        {
             if(prices[i]-cost>profit)
                 profit = prices[i] - cost;
        
             if(prices[i]<cost)
                 cost = prices[i];
        }
        return profit;
    }
}
0 0