程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 121. Best Time to Buy and Sell Stock,sellstock

121. Best Time to Buy and Sell Stock,sellstock

編輯:C++入門知識

121. Best Time to Buy and Sell Stock,sellstock


Say you have an array for which the ith element is the price of a given stock on day i.

If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.

Example 1:

Input: [7, 1, 5, 3, 6, 4]
Output: 5

max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)

 

Example 2:

Input: [7, 6, 4, 3, 1]
Output: 0

In this case, no transaction is done, i.e. max profit = 0.

 1 class Solution {
 2 public:
 3     int maxProfit(vector<int>& prices) {
 4         if(prices.size() <= 1){
 5             return 0;
 6         }
 7         
 8         int minP = prices[0];
 9         int profit = 0;
10         
11         for(int i = 1; i < prices.size(); i ++){
12             minP = min(minP, prices[i]);
13             profit = max(profit, prices[i]-minP);
14         }
15         return profit;
16     }
17 };

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved