leetcode -- Best Time to Buy and Sell Stock
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.
[解题思路]
记录一个最小值,每次拿当前值与最小值比较,如果两者差>profit,则更新profit
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 // Start typing your Java solution below 4 // DO NOT write main() function 5 int profit = 0, min = Integer.MAX_VALUE; 6 for(int i = 0; i < prices.length; i++){ 7 if(prices[i] < min){ 8 min = prices[i]; 9 } 10 if(prices[i] - min > profit){ 11 profit = prices[i] - min; 12 } 13 } 14 return profit; 15 } 16 }