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:O(n)
public class Solution { public int maxProfit(int[] prices) { int premin = Integer.MAX_VALUE; int profit=0; for(int i=0;i<prices.length;i++){ profit=Math.max(profit,prices[i]-premin); premin=Math.min(premin,prices[i]); } return profit; } }
沒有留言:
張貼留言