Closed rygh4775 closed 4 years ago
Pick up maxSum, but no adjacent index.
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);
}
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)
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];
}
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];
}
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;
}