题目大意: 给你一只股票每天的价格,如果只能做一次交易(一次买进一次卖出)问你最多能赚多少钱。
Problem:
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:
1 2 3 4 |
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:
1 2 3 4 |
Input: [7, 6, 4, 3, 1] Output: 0 In this case, no transaction is done, i.e. max profit = 0. |
Idea:
DP
Solution 1:
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Author: Huahua // Runtime: 6 ms class Solution { public: int maxProfit(vector<int>& prices) { const int n = prices.size(); if (n < 1) return 0; vector<int> min_prices(n); vector<int> max_profit(n); min_prices[0] = prices[0]; max_profit[0] = 0; for (int i = 1; i < n; ++i) { min_prices[i] = min(min_prices[i - 1], prices[i]); max_profit[i] = max(max_profit[i - 1], prices[i] - min_prices[i - 1]); } return max_profit[n - 1]; } }; |
C++ / reduce to maximum subarray
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
// Author: Huahua // Runtime: 6 ms class Solution { public: int maxProfit(vector<int>& prices) { int n = prices.size(); if (n < 2) return 0; vector<int> gains(n - 1, 0); for (int i = 1; i < n; ++i) gains[i - 1] = prices[i] - prices[i - 1]; return max(0, maxSubArray(gains)); } private: // From LC 53. Maximum Subarray int maxSubArray(vector<int>& nums) { vector<int> f(nums.size()); f[0] = nums[0]; for (int i = 1; i < nums.size(); ++i) f[i] = max(f[i - 1] + nums[i], nums[i]); return *std::max_element(f.begin(), f.end()); } }; |
Related Problems:
请尊重作者的劳动成果,转载请注明出处!花花保留对文章/视频的所有权利。
如果您喜欢这篇文章/视频,欢迎您捐赠花花。
If you like my articles / videos, donations are welcome.
Be First to Comment