LeetCode
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Solution { | |
public int maxProfit(int[] prices) { | |
if (prices==null||prices.length<2){ | |
return 0; | |
} | |
int min=Integer.MAX_VALUE; | |
int diff=0; | |
for (int i=0; i<prices.length; i++){ | |
if (prices[i]<min){ | |
min=prices[i]; | |
} | |
if (diff<prices[i]-min){ | |
diff=prices[i]-min; | |
} | |
} | |
return diff; | |
} | |
} |
No comments:
Post a Comment