• 2

Country: United States

Comment hidden because of low score. Click to expand.
2
of 2 vote

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.

``````private int getMaxProfit(int[] prices, int fee){

int maxProfit = 0;
int minPrice = prices;
int minIndex = 0;
int sellIndex = 0;
for(int i=1;i<prices.length;i++){

if(prices[i]<minPrice){
minPrice = prices[i];
minIndex =i;
}else{
if(prices[i]-minPrice-fee > maxProfit){
maxProfit = prices[i]-minPrice - fee;
sellIndex=i;
}
}
}

int[] newArray = Arrays.copyOfRange(prices, 0, buyIndex);
if(newArray.length>1)
maxProfit+=getMaxProfit(newArray, fee);
}
if(sellIndex!=prices.length-1){
int[] newArray1 = Arrays.copyOfRange(prices, sellIndex+1, prices.length);
if(newArray1.length>1)
maxProfit+=getMaxProfit(newArray1, fee);
}
return maxProfit;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

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;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````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;
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

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.sellIdx = sellIdx;
}
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)) {
i++;
} else {
}
} else {
}
}
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;
for (int i = 0; i < prices.length; i++) {
lastProfit = 0;
if (prices[i] <= lastLocalMinValue) {
lastLocalMinValue = prices[i];
lastLocalMinIx = i;
} else {
System.out.println("buy point at " + lastLocalMinIx + " for " + lastLocalMinValue);
}
}
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);
lastLocalMinValue = prices[i];
lastLocalMinIx = i;
lastLocalMaxValue = Integer.MIN_VALUE;
}
}
}
}
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);
}
}
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));
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

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++;
}

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;
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

@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));``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

we need to take difference of price of two consecutive days and store it in a array. For ex
array = price-price
array=price-price
array=price-price

Then we need to take all the subsets of this array whose maximum contiguous sum is more then the fees.

Comment hidden because of low score. Click to expand.
0
of 0 vote

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++;

}

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;
}
}``````

Comment hidden because of low score. Click to expand.
0
of 0 vote

``````#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;
}``````

Name:

Writing Code? Surround your code with {{{ and }}} to preserve whitespace.

### Books

is a comprehensive book on getting a job at a top tech company, while focuses on dev interviews and does this for PMs.

### Videos

CareerCup's interview videos give you a real-life look at technical interviews. In these unscripted videos, watch how other candidates handle tough questions and how the interviewer thinks about their performance.