噢?一脸黑人问号,这道题目怎么会比之前那题通过率更低?刷完才发现,好像解题方式完全不同,题目的含义大相径庭。
题目
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.`
prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]
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)
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
其实题目的意思很简单就是找一个数组内相差最大的两个数,要求小数必须在大数前面。所以什么动规我是不懂啦,先暴力一下!
思路
暴力思路非常简单,先遍历一遍求出第i项前面的所有最小值存进最小值数组,然后同时求出第i项后面的所有最大值存进最大值数组。然后再遍历一次求max_diff,也就是第i项后的最大值和第i项前最小值之差的最大值。
代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.size() <= 1) return 0;
vector<int> min_num(prices.size(), 0), max_num(prices.size(), 0);
min_num[0] = prices[0], max_num[prices.size()-1] = prices[prices.size()-1];
for(int l = 1; l < prices.size(); l++) {
int r = prices.size() - l - 1;
min_num[l] = min(min_num[l-1], prices[l]);
max_num[r] = max(max_num[r+1], prices[r]);
}
int max_diff = max_num[1] - min_num[0];
for(int i = 1; i < prices.size() - 1; i++) {
max_diff = max(max_diff, max_num[i+1]-min_num[i]);
}
return max(max_diff, 0);
}
};