## Myntra Interview Question

Software Engineer / Developers**Country:**India

**Interview Type:**In-Person

I went ahead and just implemented the simplest answer and here it is

```
ret[0] = a[0];
ret[1] = a[1];
for (int i = 2; i < a.length; i++){
if (ret[0] < a[i] && ret[1] > ret[0])
ret[0] = a[i];
else if (ret[1] < a[i])
ret[1] = a[i];
}
```

if line has ret[1] > ret[0] so ret[0] doesn't get changed when ret[1] is smaller than ret[0]

To solve these type of question, first thing is to find a recurring relation. In this case our recurring relation will tell the max sum till a given length. It means that we will get the max sum for running length of the array. If we denote the ith element as T(i) and max sum till ith element of the array as S(i), then

S(i) = MAX {S(i-1), S(i-2) + T(i) }

S(-1) = 0;

if i=0, S(i) = T(0);

Note: while developing this relationship, I assume array index is starting from 0.

Writing code for this problem is not a big deal now. Below is the code snippet for the same.

```
sum2 = 0;
sum = sum1 = array[0];
for(i=1; i<len; i++)
{
sum = MAX(sum2 + array[i], sum1);
sum2 = sum1;
sum1 = sum;
}
```

For a detailed explanation, visit bit.ly/ReP5zl

```
import collections
'''
Problem :
Find the subsequences whose elements should not be adjacent and their sum should be maximum from the given array (contains only positive integers).
Eg: int[] A = {10, 1, 3, 25}
Sol: Sum: {10, 3} = 13
{1,25} = 26
{10,25} = 35
Here the Maximum subsequence is {10, 25}.
Approch :
compare the adj elements and find the max and keep them in the sum array
repeat until it's length is 2 (to form a pair)
'''
def findMaxNonAdj(array):
sumList = []
temp = array
if len(array) < 2:
print "Cannot form a pair"
return
while temp:
for i in range(1,len(temp)):
sumList.append(max(temp[i-1],temp[i]))
temp = None
temp = collections.OrderedDict.fromkeys(sumList).keys()#normal sets are unorderd
print temp
sumList = list()
if len(temp) == 2:
break
print "Result "+str(temp)
def main():
nums = [10,1,3,25]
findMaxNonAdj(nums)
if __name__ == "__main__":main()
```

dp

- Anonymous October 10, 2012At i=0;

sum[0]=a[i];

sum[1]=max(a[0],a[1])

sum[i]=max(sum[i-2]+a[i],sum[i-1])

return sum[|a|-1)]