1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #include <iostream> #include <vector> using namespace std;
class Solution_0 { public: int maxProfit(vector<int>& prices) { if (prices.empty()) { return 0; } int maxProfit = 0, minPrice = INT_MAX; for (int i = 0; i < prices.size(); i++) { maxProfit = max(maxProfit, prices[i] - minPrice); minPrice = min(minPrice, prices[i]); } return maxProfit; } };
class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); vector<vector<int>> f(n, vector<int>(2));
for (int i = 0; i < n; i++) { if (i == 0) { f[i][0] = 0; f[i][1] = -prices[i]; continue; } else { f[i][0] = max(f[i-1][0], f[i-1][1] + prices[i]); f[i][1] = max(f[i-1][1], -prices[i]); } }
return f[n-1][0]; } };
class Solution_2 { public: int maxProfit(vector<int>& prices) { int n = prices.size(); int f_i0 = 0; int f_i1 = INT_MIN;
for (int i = 0; i < n; i++) { f_i0 = max(f_i0, f_i1 + prices[i]); f_i1 = max(f_i1, -prices[i]); }
return f_i0; } };
void printArray(const vector<int>& nums) { cout << "["; for (size_t i = 0; i < nums.size(); i++) { cout << nums[i]; if (i != nums.size() - 1) cout << ","; } cout << "]"; }
int main() { Solution solution; vector<vector<int>> prices_cases = { {7,1,5,3,6,4}, {7,6,4,3,1} };
for (auto& prices : prices_cases) { cout << "Input: prices = "; printArray(prices); cout << endl;
int result = solution.maxProfit(prices); cout << "Output: " << result << endl; }
return 0; }
|