v32
BAN USERXOR, AND and OR bitwise can solve. Assuming both arrays sent are of same length (we can add more code based on whichever is max length and XOR with 0 if min length). This would print (return array) of bits.
public int[] bitAddition(int[] num1, int[] num2) {
int sum[] = new int[num1.length + 1];
int i = 0, carry =0;
for ( i = num1.length-1; i >= 0; i--) {
sum[i+1] = num1[i] ^ num2[i] ^ carry;
carry = (num1[i] & num2[i]) | (num1[i] & carry) | (num2[i] & carry);
}
sum[0] = carry;
return sum;
}
We can do this only with min and profit. Also, if its mandatory to return negative profit, that also needs to consider. e.g {22, 19}, should this return as -3? I assumed we dont have to buy and sell if there is negative profit and return 0 in that case. if interviewer insist, we can change last line to return negative.
public int findMaxProfit(int[] estimatedStocks) {
int min = estimatedStocks[0];
int profit = Integer.MIN_VALUE;
for(int i=1; i< estimatedStocks.length; i++) {
if(profit < estimatedStocks[i] - min)
profit = estimatedStocks[i] - min;
if(estimatedStocks[i] < min)
min =estimatedStocks[i];
}
return profit > 0 ? profit : 0;
}
Java. Just keep two pointers and run front and back checking data of these pointers.
- v32 February 20, 2017