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:
loop through entire list and catch min_price and the position of this this price, when current reached price's position after min_price's position then do calculate difference and up max_profit
Solution:
loop through entire list and catch min_price and the position of this this price, when current reached price's position after min_price's position then do calculate difference and up max_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
/* | |
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; | |
} | |
} |
No comments:
Post a Comment