interview-preparation / what-we-do

0 stars 8 forks source link

[Hard] interview questions #16 #169

Closed rygh4775 closed 4 years ago

rygh4775 commented 4 years ago

image

rygh4775 commented 4 years ago

Description

Pick up maxSum, but no adjacent index.

Sample Inputs

Expected Outputs

Solutions

1: Recursive

int maxMinutes(int[] massages) {
  return maxMinutes(messages, 0);
}

int maxMinutes(int[] masseages, int index) {
  if (index >= messages.length) {
    return 0;
  }

  int bestWith = masseages[index] + maxMinutes(masseages, index + 2);

  int bestWithout = maxMinutes(massages, index + 1);

  return Math.max(bestWith, bestWithout);
}

Call stacks

message length: 5

(0)
  (2)
    (4)
      (6)
      (5)
    (3)
      (5)
      (4)
        (6)
        (5)
  (1)
    (3)
      (5)
      (4)
        (6)
        (5)
    (2)
        (4)
          (6)
          (5)
      (3)
        (5)
        (4)
          (6)
          (5)

2: Recursive + Memoization

int maxMinutes(int[] massages) {
  int[] memo = new int[massages.length];
  return maxMinutes(messages, 0);
}

int maxMinutes(int[] masseages, int index, int[] memo) {
  if (index >= messages.length) {
    return 0;
  }

  if (memo[index] == 0) {
    int bestWith = masseages[index] + maxMinutes(masseages, index + 2);
    int bestWithout = maxMinutes(massages, index + 1);
    memo[index] = Math.max(bestWith, bestWithout);  
  }

  return memo[index];
}

3: Iterative: w/o call stack

0 1 2 3 4 5 6 7
30 15 60 75 45 15 15 45
int maxMinutes(int[] massages) {
  int[] memo = new int[messages.length + 2];
  memo[massages.length] = 0;
  memo[massages.length + 1] = 0;

  for(int i = memo.length; i >= 0; i--) {
    int bestWith = messages[i] + memo[i+2];
    int bestWithout = messages[i+1];
    memo[i] = Math.max(bestWith, bestWithout);
  }

  return memo[0];
}

4: Iterative: w/o call stack + memoization

int maxMinutes(int[] massages) {
  int[] memo = new int[messages.length + 2];
  memo[massages.length] = 0;
  memo[massages.length + 1] = 0;
  int oneAway = 0;
  int twoAway = 0;

  for(int i = memo.length; i >= 0; i--) {
    int bestWith = messages[i] + twoAway;
    int bestWithout = oneAway;
    int current = Math.max(bestWith, bestWithout);
    twoAway = oneAway;
    oneAway = current;
  }

  return oneAway;
}