fork download
  1. #include <iostream>
  2.  
  3. using namespace std;
  4.  
  5. void houseRobbery(int houseCount, unsigned long *maxSum, unsigned long *initialHouses) {
  6. /*
  7. A function that, through dynamic programming, calculates the maximum production of houses not standing nearby.
  8. The function does not return anything, since it modifies arrays through pointers
  9. */
  10.  
  11. // Initial state values for the first two houses
  12. maxSum[0] = initialHouses[0];
  13. maxSum[1] = max(initialHouses[0], initialHouses[1]);
  14.  
  15. // Since by condition it is given that we cannot rob two houses in a row,
  16. // then we will take the maximum house of two: maxSum[i - 1] and maxSum[i - 2] + initialHouses[house]
  17. // (where initialHouses[house] is the amount of money in the i-th house)
  18. for (int house = 2; house < houseCount; house += 1) {
  19. maxSum[house] = max(maxSum[house - 1], maxSum[house - 2] + initialHouses[house]);
  20. }
  21. }
  22.  
  23. int main() {
  24. int houseCount;
  25. cin >> houseCount;
  26.  
  27. // Initialize the arrays not containing negative values
  28. unsigned long initialHouses[houseCount], maxSum[houseCount];
  29.  
  30. // Filling the initial array of houses with user input
  31. for (int element = 0; element < houseCount; element += 1) {
  32. cin >> initialHouses[element];
  33. }
  34.  
  35. // Calling the function
  36. houseRobbery(houseCount, maxSum, initialHouses);
  37.  
  38. cout << maxSum[houseCount - 1];
  39. return 0;
  40. }
Success #stdin #stdout 0.01s 5516KB
stdin
5
6 1 2 10 4
stdout
16