Guest User

Untitled

a guest
Nov 17th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.12 KB | None | 0 0
  1. #include "pch.h"
  2. #include <iostream>
  3. #include <algorithm>
  4. #include <string>
  5. #include <vector>
  6. #include <time.h>
  7.  
  8. using namespace std;
  9.  
  10. int get_max_profit(vector<int> prices);
  11.  
  12. int main()
  13. {
  14. vector<int> prices(10);
  15.  
  16. prices = { 25, 7, 5, 8, 11, 9 };
  17. int m_profit = get_max_profit(prices);
  18. //returns 6 (buying for 5 and selling for 11)
  19. cout << "1st:the max profit should be 6: " << m_profit << endl;
  20.  
  21. prices = { 10, 7, 11, 5, 8, 9 };
  22. m_profit = get_max_profit(prices);
  23. //returns 4 (buying for 7 and selling for 11, or buying for 5 and selling for 9)
  24. cout << "2nd:the max profit should be 4: " << m_profit << endl;
  25.  
  26. prices = { 10, 7, 11, 5, 8, 7 };
  27. m_profit = get_max_profit(prices);
  28. //returns 6 (buying for 7 and selling for 11)
  29. cout << "3rd:the max profit should be 4: " << m_profit << endl;
  30.  
  31. prices = { 10, 7, 9, 5, 8, 7 };
  32. m_profit = get_max_profit(prices);
  33. //returns 6 (buying for 5 and selling for 8)
  34. cout << "4th:the max profit should be 3: " << m_profit << endl;
  35.  
  36. prices = { 10, 7, 9, 5, 8, 7 };
  37. m_profit = get_max_profit(prices);
  38. //returns 6 (buying for 5 and selling for 8)
  39. cout << "5th:the max profit should be 3: " << m_profit << endl;
  40.  
  41. prices = { 16, 9, 7, 5, 3, 10 };
  42. m_profit = get_max_profit(prices);
  43. //returns 6 (buying for 3 and selling for 10)
  44. cout << "6th:the max profit should be 7: " << m_profit << endl;
  45.  
  46. //To test performance
  47. srand(unsigned(time(NULL)));
  48. prices.resize(10000000);
  49. generate(prices.begin(), prices.end(), rand);
  50. clock_t t_start = clock();
  51. m_profit = get_max_profit(prices);
  52. clock_t t_end = clock();
  53. cout << "Final:the max profit from a random array with 10,000,000 numbers: " << m_profit << endl;
  54. cout << "Time used: " << ((t_end - t_start) / CLOCKS_PER_SEC) << " seconds" << endl;
  55. }
  56.  
  57. //this is to get the max gap in an array supposing gap can only be a later number minus a former number
  58. int get_max_profit(vector<int> prices) {
  59. int currMax = 0;
  60. int totalMax = 0;
  61.  
  62. int count_prices = prices.size();
  63. if (count_prices <= 1) {
  64. return 0;
  65. }
  66.  
  67. for (int i = 1; i < count_prices; i++) {
  68. currMax = max(0, currMax + prices[i] - prices[i - 1]);
  69. totalMax = max(totalMax, currMax);
  70. }
  71. return totalMax;
  72. }
Add Comment
Please, Sign In to add comment