## Flipkart Interview Question

Senior Software Development Engineers**Team:**digital

**Country:**India

**Interview Type:**Phone Interview

```
public static void findMaxStockProfit(int[] arr) {
int maxSum = Integer.MIN_VALUE;
int maxSumStartIndx = 0;
int maxSumEndIndx = 0;
int lastMinValueIndx = 0;
int curIndx = 0;
while(curIndx < arr.length) {
int diff = arr[curIndx] - arr[lastMinValueIndx];
if(diff > maxSum) {
maxSum = diff;
maxSumStartIndx = lastMinValueIndx;
maxSumEndIndx = curIndx;
}
if(arr[lastMinValueIndx] > arr[curIndx]) {
lastMinValueIndx = curIndx;
}
curIndx++;
}
System.out.println("MaxSum = " + maxSum + ". StartIndx = " + maxSumStartIndx + ". EndIndx = " + maxSumEndIndx);
}
```

Very interesting problem. Lets scan the array and find out if we sold the share next day what would be our profit(+) or loss(-). So the new array is

-65,-11,18,83,-60,-42.-3,85,-93,95,5,-96

Now scan the array from left to right and keep summing continuous +ives and store it in a variable max. If the next continuous +ive sum is > max then store that value in max. At the end of the scan we will have the max output. Complexity O(n)

{

private static void calcDiff2(int[] input) {

Arrays.sort(input);

int maxDiff = 0;

for (int i = 0; i < input.length; i++) {

for (int j = i + 1; j < input.length; j++) {

int diff = input[j] - input[i];

if (diff > maxDiff) {

maxDiff = diff;

}

}

}

System.out.println("Max Difference is (2) --> " + maxDiff);

}

private static void calcDiff1(int[] input) {

int maxDiff = 0;

for (int i = 0; i < input.length; i++) {

for (int j = 0; j < input.length; j++) {

int diff = input[i] - input[j];

if (diff > maxDiff) {

maxDiff = diff;

}

}

}

System.out.println("Max Difference is (1) --> " + maxDiff);

}

}

- Vishal S Kumar February 12, 2014