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

LeetCode:Best Time to Buy and Sell Stock

編輯:C++入門知識

LeetCode:Best Time to Buy and Sell Stock


題目描述:

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.


思路:遍歷數組,保存已經遍歷過了的元素的最小值low。則在第i天賣出股票所能得到的最大收益為prices[i]-low,求出每天最大收益的最大值即可。


代碼:

int maxProfit(vector &prices)
{
    int length = prices.size();
    if(length == 0)
        return 0;
    int max_profit = 0;
    int low = prices[0];
    for(int i = 1;i < length;i++)
    {
        int temp = prices[i] - low;
        if(temp > max_profit)
            max_profit = temp;
        if(prices[i] < low)
            low = prices[i];
    }
    return max_profit;
}


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