问题描述:
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.
Example 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0In this case, no transaction is done, i.e. max profit = 0.
分析问题:
找出一个无序的数组中,后面一个数减去前面一个数中差最大的,如果差最大小于0,那么返回0.
第一反应是暴力解法,时间复杂度是O(n^2).
代码实现
public int maxProfit(int[] prices) {
int max = Integer.MIN_VALUE;
for (int i = 0; i < prices.length; i++) {
for (int j = i + 1; j < prices.length; j++) {
int profit = prices[j] - prices[i];
max = Math.max(profit, max);
}
}
return Math.max(0, max);
}
算法改进
这个算法本质是找出一个最小的值,然后用后面的值减这个最小的值,计算出最大的差。可以使用一个标记为标记最小的价格,然后不断的往后去求差。时间复杂度能够降到O(n).
代码实现
public int maxProfit(int[] prices) {
if (prices == null || prices.length == 0) {
return 0;
}
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int i = 0; i < prices.length; i++) {
if (minPrice > prices[i]) {
minPrice = prices[i];
}else{
int nowProfit = prices[i] - minPrice;
maxProfit = nowProfit > maxProfit ? nowProfit : maxProfit;
}
}
return maxProfit;
}