Created
June 27, 2014 04:51
-
-
Save Ray1988/7a503b551c5bb18c84c9 to your computer and use it in GitHub Desktop.
Java
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
/* | |
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. | |
*/ | |
public class Solution { | |
public int maxProfit(int[] prices) { | |
if (prices==null || prices.length==0){ | |
return 0; | |
} | |
int min_price=Integer.MAX_VALUE; | |
int min_position=0; | |
int max_profit=0; | |
for (int i=0;i<prices.length; i++){ | |
if (prices[i]<min_price){ | |
min_price=prices[i]; | |
min_position=i; | |
} | |
if (i>min_position){ | |
max_profit=Math.max(max_profit, prices[i]-min_price); | |
} | |
} | |
return max_profit; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment