main.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /* Harry is a postman. He's got a post office with a size of n*m(a matrix / 2D array). Each slot at the 2D array
  2. * represents the number of letters in that spot. Harry can only go right and down. He starts at (0, 0), and ends at (n-1, m-1).
  3. * n represents the height, and m the length. Return the maximum amount of letters he can pick up. He can only pick up letters if he is on that spot.
  4. * Examples
  5. * harry(2, 2, [[5, 2], [5, 2]]) ➞ 12
  6. * (5+5+2)
  7. * harry(3, 5, [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15]]) ➞ 72
  8. * (1+6+11+12+13+14+15)
  9. * harry(0, 0, [[]]) ➞ -1
  10. * Notes
  11. * Like you saw in example 3, if the matrix is empty, return -1.
  12. * If the amount of letters is the same down and right, go right.
  13. * You can't go down if you're on the bottom row, or right if you're on the most right column.
  14. *
  15. *
  16. * After solving this problem, we realized that one of the tests the writer made would always cause a failure. The unit tests did not match the instructions.
  17. */
  18. #include <QCoreApplication>
  19. int harry(int n, int m, std::vector<std::vector<int> > vv);
  20. int main(int argc, char *argv[])
  21. {
  22. QCoreApplication a(argc, argv);
  23. int answer = harry(5,5,std::vector<std::vector<int> >({{5,6,2,5,1},{7,2,4,1,2},{0,7,5,2,14},{9,5,12,5,9},{19,5,2,6,2}}));
  24. return a.exec();
  25. }
  26. int harry(int n, int m, std::vector<std::vector<int> > vv){
  27. int lett = 0;
  28. if (vv.empty()) return -1;
  29. for (int i = 0; i < n; i++){
  30. for (int j = 0; j < m; j++){
  31. if (i == vv.size()-1 && j == vv[i].size()-1) return lett;
  32. if (i == vv.size()-1) lett+=vv[i][j+1];
  33. else if (i == vv[i].size()-1) lett+=vv[i+1][j];
  34. else {if (vv[i+1][j] > vv[i][j+1]) lett+=vv[i+1][j]; else lett+=vv[i][j+1];}
  35. }
  36. }
  37. return lett;
  38. }