Google Interview Question
Country: United States
Just go starting from the end of the array and check if we see the a bigger stock price we memorize it, else we check if we can profit from buying on ith day to sell on maxPrice day.
int maxProfit(int[] prices, int fee) {
int profit = 0;
int maxPrice = -1;
for(int i = prices.length-1; i>=0; i--) {
if(a[i] > maxPrice) maxPrice = a[i];
else {
int tmpProfit = maxPrice - a[i] - fee;
if(tmpProfit > 0)
profit +=tmpProfit;
}
}
return profit;
}
public static int maxProfit(int[] prices, int fee) {
if(prices.length==0)
return 0;
int min=0;
int max=0;
int curprofit=0;
int prevprofit=0;
for(int i=1;i<prices.length;i++){
if(prices[i]>prices[max]){
if(prices[i]-prices[min]-fee>=0){
curprofit= prevprofit + prices[i]-prices[min]-fee;
}
max=i;
}
else if(prices[i]<=prices[max]){
min=i;
prevprofit= curprofit;
max=i;
}
}
return curprofit;
}
The previous solution of @PPD fails with check with this:
assertEquals(15, Stock.getMaxProfit(new int[] {1,7,1,7,1,7,10}, 2));
I propose something more complex but seems to work:
public class Stock {
static class TransactionPair {
public TransactionPair(int buyIdx, int sellIdx) {
this.buyIdx = buyIdx;
this.sellIdx = sellIdx;
}
int buyIdx;
int sellIdx;
}
public static int maxProfit(int[] prices, int fee) {
List<TransactionPair> transactionPairs = smallTransactions(prices, fee);
List<TransactionPair> mergedTransactions = mergeTransactionsLoop(transactionPairs, prices, fee);
int profit = calcProfit(mergedTransactions, prices, fee);
System.out.println("profit = " + profit);
System.out.println();
return profit;
}
private static List<TransactionPair> mergeTransactionsLoop(List<TransactionPair> transactionPairs, int[] prices, int fee) {
int pairNo;
List<TransactionPair> trMergerd = null;
List<TransactionPair> trBeforeMerge = transactionPairs;
do {
pairNo = trBeforeMerge.size();
System.out.println("profit before merge= " + calcProfit(trBeforeMerge, prices, fee));
trMergerd = mergeTransactions(trBeforeMerge, prices, fee);
trBeforeMerge = trMergerd;
} while (pairNo > trMergerd.size());
return trMergerd;
}
private static List<TransactionPair> mergeTransactions(List<TransactionPair> transactionPairs, int[] prices, int fee) {
List<TransactionPair> mergedTransactions = new ArrayList<>();
for (int i = 0; i < transactionPairs.size(); i++) {
if (i < (transactionPairs.size() - 1)) {
TransactionPair merged = new TransactionPair(transactionPairs.get(i).buyIdx, transactionPairs.get(i + 1).sellIdx);
if (calcTrasactionProfit(prices, fee, transactionPairs.get(i)) + calcTrasactionProfit(prices, fee, transactionPairs.get(i + 1))
< calcTrasactionProfit(prices, fee, merged)) {
mergedTransactions.add(merged);
i++;
} else {
mergedTransactions.add(transactionPairs.get(i));
}
} else {
mergedTransactions.add(transactionPairs.get(i));
}
}
return mergedTransactions;
}
private static int calcProfit(List<TransactionPair> transactionPairs, int[] prices, int fee) {
return transactionPairs.stream().mapToInt(tr -> calcTrasactionProfit(prices, fee, tr)).sum();
}
private static int calcTrasactionProfit(int[] prices, int fee, TransactionPair tr) {
return prices[tr.sellIdx] - prices[tr.buyIdx] - fee;
}
private static List<TransactionPair> smallTransactions(int[] prices, int fee) {
List<TransactionPair> transactionPairs = new ArrayList<>();
int lastProfit = 0;
int lastLocalMinValue = Integer.MAX_VALUE;
int lastLocalMinIx = -1;
int lastLocalMaxValue = Integer.MIN_VALUE;
int lastLocalMaxIx = -1;
boolean lookToBuy = true;
for (int i = 0; i < prices.length; i++) {
System.out.println(String.format("prices(%d)=%d, %b", i, prices[i], lookToBuy));
if (lookToBuy) {
lastProfit = 0;
if (prices[i] <= lastLocalMinValue) {
lastLocalMinValue = prices[i];
lastLocalMinIx = i;
} else {
lookToBuy = false;
System.out.println("buy point at " + lastLocalMinIx + " for " + lastLocalMinValue);
}
}
if (!lookToBuy) {
if (prices[i] >= lastLocalMaxValue) {
lastLocalMaxValue = prices[i];
lastLocalMaxIx = i;
} else {
int diff = lastLocalMaxValue - lastLocalMinValue;
if (diff > fee && (diff - fee) > lastProfit) {
lastProfit = diff - fee;
System.out.println("sell point at " + lastLocalMaxIx + " for " + lastLocalMaxValue + " profit is " + lastProfit);
lookToBuy = true;
transactionPairs.add(new TransactionPair(lastLocalMinIx, lastLocalMaxIx));
lastLocalMinValue = prices[i];
lastLocalMinIx = i;
lastLocalMaxValue = Integer.MIN_VALUE;
}
}
}
}
if (!lookToBuy) {
int diff = prices[prices.length - 1] - lastLocalMinValue;
if (diff > fee && (diff - fee) > 0) {
lastProfit = diff - fee;
System.out.println("sell point at the end, profit " + lastProfit);
transactionPairs.add(new TransactionPair(lastLocalMinIx, prices.length - 1));
}
}
return transactionPairs;
}
public static void main(String[] args) {
assert(3 == Stock.maxProfit(new int[] {3,3,2,6}, 1));
assert(3 == Stock.maxProfit(new int[] {3,3,2,6,5,5}, 1));
assert(0 == Stock.maxProfit(new int[] {9,8,7,6,5,4}, 1));
assert(0 == Stock.maxProfit(new int[] {1,1,1,1,1,1}, 1));
assert(2 == Stock.maxProfit(new int[] {1,1,3,4,3,1}, 1));
assert(4 == Stock.maxProfit(new int[] {1,2,3,4,5,6}, 1));
assert(3 == Stock.maxProfit(new int[] {1,2,3,4,3,1,2,3,1}, 1));
assert(7 == Stock.maxProfit(new int[] {1,10,8,2}, 2));
assert(8 == Stock.maxProfit(new int[] {1,10,2,5}, 2));
assert(5 == Stock.maxProfit(new int[] {2,2,1,2,3,2,3,4,3,4,5,4,5,6,5,6,8,6}, 2));
assert(7 == Stock.maxProfit(new int[] {2,2,1,2,3,2,3,4,3,4,5,4,5,6,5,6,7,6,7,8,7,8,9,8,9,10}, 2));
assert(8 == Stock.maxProfit(new int[] {2,2,1,2,3,2,3,4,3,4,5,4,5,6,5,6,7,6,7,8,7,8,9,8,9,10,2,5}, 2));
assert(15 == Stock.maxProfit(new int[] {1,7,1,7,1,7,10}, 2));
}
}
Imagine plotting the values on a coordinate axis. There will several local minimums and local maximums. You can buy at a local minimum and sell at a local maximum if the difference is greater than the fee
public static int maxProfit(int[] prices, int fee) {
int maxProfit = 0;
int i = 1;
int currentMin = Integer.MAX_VALUE;
while (i < prices.length) {
// find the local minimum
while (i<prices.length && prices[i] <= prices[i-1]) {
i++;
}
// now buy the stock
if (currentMin==Integer.MAX_VALUE) currentMin = prices[i-1];
// find the local maximum
while (i<prices.length && prices[i] >= prices[i-1]) {
i++;
}
// now sell the stock
if (prices[i-1] - currentMin > fee) {
maxProfit+=prices[i-1]-currentMin-fee;
currentMin = Integer.MAX_VALUE;
}
}
@challapallirahul I started with the same idea, but it is not enough,
the problem is if you have period with several little profits whereas buying once for the whole period gives better profit. Below tests that your algorithm do not pass:
assertEquals(5, Stock.maxProfit(new int[] {2,2,1,2,3,2,3,4,3,4,5,4,5,6,5,6,8,6}, 2));
assertEquals(7, Stock.maxProfit(new int[] {2,2,1,2,3,2,3,4,3,4,5,4,5,6,5,6,7,6,7,8,7,8,9,8,9,10}, 2));
assertEquals(8, Stock.maxProfit(new int[] {2,2,1,2,3,2,3,4,3,4,5,4,5,6,5,6,7,6,7,8,7,8,9,8,9,10,2,5}, 2));
Thanks @kryzoo.m for pointing out flaws in my execution. Below is the revised approach
1. Find local minimums and local maximums. Each min and max will form an interval
2. See if you can merge current interval with the previous one, otherwise the previous interval can used as a min and max of your transaction
public static int maxProfit(int[] prices, int fee) {
int maxProfit = 0;
List<Interval> intervals = new ArrayList<Interval>();
int i=0;
while (i<prices.length-1) {
// find the local minima
while (i<prices.length-1 && prices[i]>=prices[i+1])
i++;
if (i==prices.length-1) break;
int min = prices[i];
// find the local maxima
while (i<prices.length-1 && prices[i] <= prices[i+1])
i++;
intervals.add(new Interval(min, prices[i]));
}
if (intervals.size()==0) return 0;
Interval merge=null;
for (int j=0; j<intervals.size(); j++) {
if (merge == null) {
merge = intervals.get(j);
continue;
}
// check if current interval can be merged with the merge interval
if (merge.max - intervals.get(j).min <= fee && intervals.get(j).max > merge.max) {
merge.max = intervals.get(j).max;
} else {
// consume the interval
maxProfit+=merge.max-merge.min-fee;
merge = intervals.get(j);
}
}
if (merge!=null) maxProfit+=merge.max-merge.min-fee;
return maxProfit;
}
public static class Interval {
int min;
int max;
public Interval (int s, int e) {
min = s;
max = e;
}
}
#include <unordered_map>
#include <vector>
#include <iostream>
using namespace std;
int MaxProfit(const vector<int>& a, int fee, unordered_map<uint64_t, int>& memo, int bought = -1, int idx = 0)
{
if (idx < 0 || idx >= a.size())
{
return 0;
}
if (bought == -1)
{
return max(
MaxProfit(a, fee, memo, a[idx], idx + 1),
MaxProfit(a, fee, memo, -1, idx + 1)
);
}
uint64_t memo_key = (static_cast<uint64_t>(bought) << 32) | idx;
auto it = memo.find(memo_key);
if (it != memo.end())
{
return it->second;
}
int res = 0;
int sell_profit = a[idx] - bought - fee;
if (sell_profit > 0)
{
res = sell_profit + MaxProfit(a, fee, memo, -1, idx + 1);
}
res = max(res, MaxProfit(a, fee, memo, bought, idx + 1));
memo[memo_key] = res;
return res;
}
int main()
{
unordered_map<uint64_t, int> memo;
cout << MaxProfit({3, 5, 7, 9, 8, 2, 1, 3}, 1, memo) << "\n";
return 0;
}
Iterate through the list and find the max profit with one transaction.
Remember the index of buy and sell index for the max profit and then recursively calculate the profit with the sub array for values before the sell index and after the sell index.
- PPD March 11, 2017