# LeetCode : 0121. Best Time to Buy and Sell Stock (array) ###### tags:`leetcode` ``` #include <bits/stdc++.h> #include <iostream> #include <vector> #include <unordered_map> using std::vector; using std::unordered_map; using namespace std; class BaseVectorPrint { public: void BasePrint00(vector<int>& num) { for (size_t i = 0; i < num.size(); ++i) { cout << "[" <<num.at(i) << "]" << "; "; } cout << endl; } void BasePrint01(vector<int>& num) { for (size_t i = 0; i < num.size(); ++i) { cout << num[i] << "; "; } cout << endl; } void BasePrint02(vector<int>& num) { for (const auto &item : num) { cout << item << "; "; } cout << endl; } void TwoDimensionalPrint(vector<vector<int>> &num){ for (int i = 0; i < num.size(); i++) { for (int j = 0; j < num[i].size(); j++) { cout << "[" << num[i][j] << "]"; } cout << endl; } } }; class BaseSolution { public: int maxProfit(vector<int>& prices) { int days = prices.size(); int maxprofit = 0; int profit = 0; for(int i = 0 ; i < (days-1) ; i++){ for (int j = i+1 ; j < days ; j++){ profit = prices[j] - prices[i]; //cout << "day " << i <<endl; cout << "profit" << profit << endl; if(profit > maxprofit){ maxprofit = profit; cout << "maxprofit = " << maxprofit << endl; } } } return maxprofit; } //Time complexity: O(n^2) //Space complexity: O(1) }; class Solution01 { public: int maxProfit(vector<int>& prices) { if(prices.empty()) return 0; int minprice = prices[0], int profitmax = 0; for(int i = 1; i < prices.size(); i++){ //minprice = min(minprice, prices[i]); if (minprice > prices[i]){ minprice = prices[i]; } if (profitmax < (prices[i] - minprice)){ profitmax = prices[i] - minprice; } //profit = max(profit, prices[i] - minprice); } return profitmax; } //Time complexity: O(n) //Space complexity: O(1) }; int main(void) { BaseVectorPrint printVector; BaseSolution buy_and_sell_stock; Solution01 better_run; int ans = 0; vector<int> priceList01 = {7,1,5,3,6,4}; vector<int> priceList02 = {7,6,4,3,1}; //ans = buy_and_sell_stock.maxProfit(priceList01); ans = better_run.maxProfit(priceList01); cout << "maxProfit = " << ans << endl; printf("test\n"); system("pause"); } ``` > save minprice space , use only one loop