题目:
Say you have an array for which the ith element is the price of a given stock on dayi.
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.
题解:
Divide and Conquer。把数组分两半,最大利润为左半边的最大利润,或右半边的最大利润,或右边最大的价格减去左边最小的价格。以此递归。
C++版,不太Elegant啊。
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(!prices.size())
return 0;
vector<int> left = profitRecur(prices, 0, (prices.size()-1)/2);
vector<int> right = profitRecur(prices, (prices.size()+1)/2, prices.size()-1);
int maxProfit = 0;
maxProfit = max(left[0], right[0]);
maxProfit = max(maxProfit, right[2] - left[1]);
return maxProfit;
}
vector<int> profitRecur(vector<int> &prices, int start, int end) {
vector<int> results(3);
if(start >= end) {
results[0] = 0;
results[1] = prices[start];
results[2] = prices[start];
} else if(end - start == 1) {
results[0] = prices[start] <= prices[end] ? prices[end] - prices[start] : 0;
results[1] = min(prices[start], prices[end]);
results[2] = max(prices[start], prices[end]);
} else {
vector<int> left = profitRecur(prices, start, (start+end)/2);
vector<int> right = profitRecur(prices, (start+end)/2 + 1, end);
results[0] = max(left[0], right[0]);
results[0] = max(results[0], right[2]-left[1]);
results[1] = min(left[1], right[1]);
results[2] = max(left[2], right[2]);
}
return results;
}
};
网上学来了快捷方法:追踪当前最大利润和全局最大利润,与计算子串最大和的方法相同。
Java版:
public class Solution {
public int maxProfit(int[] prices) {
if(prices.length == 0)
return 0;
int localMax = 0, globalMax = 0;
for(int i = 1; i < prices.length; i++) {
if(localMax <= 0)
localMax = prices[i] - prices[i-1];
else
localMax += prices[i] - prices[i-1];
if(localMax > globalMax)
globalMax = localMax;
}
return globalMax;
}
}
Python版:
class Solution:
# @param prices, a list of integer
# @return an integer
def maxProfit(self, prices):
if len(prices) == 0:
return 0
localMax = 0
globalMax =0
for i in range(1, len(prices)):
if localMax <= 0:
localMax = prices[i] - prices[i-1]
else:
localMax += prices[i] - prices[i-1]
if localMax > globalMax:
globalMax = localMax
return globalMax
五个月后重写,比起第一次写,果然有进步啊!
class Solution {
public:
int maxProfit(vector<int> &prices) {
if(prices.size() == 0)
return 0;
int curLow = prices[0];
int* global = new int[prices.size()];
global[0] = 0;
for(int i = 1; i < prices.size(); i++) {
global[i] = max(global[i-1], prices[i]-curLow);
if(prices[i] < curLow)
curLow = prices[i];
}
return global[prices.size()-1];
}
};