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.
Analysis:
1. Track the minimum value which has been encountered currently andthe maximum value of the profit.
2. Each time a new value encountered, the maximum value it can obtain should be new_value - minimum_value. This result should be compared with maximum profit.
Update 12/01/2014:
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length<=1) return 0;
int min = prices[0];
int profit = 0;
for(int i=1; i<prices.length; i++) {
if(prices[i]-min>profit) profit=prices[i]-min;
if(prices[i]<min) min=prices[i];
}
return profit;
}
}
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length <= 1) {
return 0;
}
int min = prices[0];
int profit = 0;
for(int i=1; i<prices.length; i++) {
if(prices[i] - min > profit) {
profit = prices[i] - min;
}
if(prices[i] < min) {
min = prices[i];
}
}
return profit;
}
}
本文介绍了一种寻找股票交易中最大利润的算法。该算法通过跟踪遍历过程中的最小值和最大利润,实现了一次遍历即可确定最佳买卖时机的目标。适用于只允许进行一次买卖的情况。
679

被折叠的 条评论
为什么被折叠?



