1+ /* 
2+  * You are provided a vector of numbers, where each number represents 
3+  * price of a stock on ith day. If you are permitted to only complete 
4+  * one transaction per day (i.e buy one and sell one stock), design 
5+  * an algorithm to find the maximum profit. 
6+  *  
7+  * Input: [7, 1, 5, 3, 6, 4] 
8+  * Output: 5  
9+  * max. difference = 6-1 = 5 
10+  * (not 7-1 = 6, as selling price needs to be larger than buying price) 
11+  *  
12+  * Approach: 
13+  *  
14+  * We need to find the maximum difference between two numbers in the array 
15+  * (which would be maximum profit) such that selling price(second number) 
16+  *  is bigger than buying price. 
17+  */  
18+ 
19+ #include  < iostream> 
20+ #include  < vector> 
21+ #include  < limits> 
22+ 
23+ int  maximum_profit (const  std::vector<int >& prices)
24+ {
25+     int  min_price = std::numeric_limits<int >::max ();
26+     int  max_profit = 0 ;
27+     for  (int  i = 0 ; i < prices.size (); ++i) {
28+         if  (prices[i] < min_price) {
29+             min_price = prices[i];
30+         } else  if  (prices[i] - min_price > max_profit) {
31+             max_profit = prices[i] - min_price;
32+         }
33+     }
34+     return  max_profit;
35+ }
36+ 
37+ void  print_vector (const  std::vector<int >& vec) {
38+     for  (auto  v : vec) {
39+         std::cout << v << "  "  ;
40+     }
41+     std::cout << std::endl;
42+ }
43+ 
44+ int  main ()
45+ {
46+     std::vector<int > prices{7 , 1 , 5 , 3 , 6 , 4 };
47+     std::cout << " Prices of stocks in last "   << prices.size ()
48+         << "  days:"   << std::endl;
49+     print_vector (prices);
50+     std::cout << " Maximum profit: "   << maximum_profit (prices)
51+         << std::endl;
52+ 
53+     return  0 ;
54+ }
0 commit comments