leetcode#121#122#123 Best Time to Buy and Sell Stock

来源:互联网 发布:快递单号记录软件 编辑:程序博客网 时间:2024/06/10 14:05

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

#121 只买入卖出各一次,选取到今天为止最小值为买入价,比较今后的卖出价格的收益和之前记录的收益。

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.

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

int maxProfit121(vector<int>& prices) {int n = prices.size();if (n <= 1) return 0;int minPrice = prices[0];int profit = 0;for (int i = 1; i < n; i++){minPrice = min(minPrice, prices[i]);if (profit < prices[i] - minPrice)profit = prices[i] - minPrice;}return profit;}

#122 买入前必须卖出已有股票,不可以连续买入两天,每次交易表示为前一天价格买入,当前价格卖出。

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Input: [7,1, 5, 3, 6, 4]Output:(5-1) + (6-3) = 7

int maxProfit122(vector<int>& prices) {int n = prices.size();if (n <= 1)return 0;int profit = 0;for (int i = 1; i < n; i++){if (prices[i] > prices[i - 1])profit += prices[i] - prices[i - 1]; //前一天价格买入,当天卖出。不可以连续买入。}return profit;}


#123 交易次数最多为两次,分别用两个vector动态记录从[0,i], [i, n-1]的最大收益

Design an algorithm to find the maximum profit. You may complete at most two transactions.You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

Input: [7,1, 5, 3, 6, 4]Output: 7
int maxProfit123(vector<int>& prices) {int n = prices.size();if (n <= 1)return 0;int profit = 0;vector<int> p1(n); //记录[0,i]内买卖最大收入vector<int> p2(n); //记录[i,n-1]内买卖最大收入int buyPrice = prices[0]; //从前往后遍历,当前值为买入价int sellPrice = prices[n - 1]; //从后往前遍历,当前值为卖出价for (int i = 1; i < n; i++){buyPrice = min(buyPrice, prices[i]);p1[i] = max(p1[i - 1], prices[i] - buyPrice);}for (int i = n - 2; i >= 0; i--){sellPrice = max(sellPrice, prices[i]);p2[i] = max(p2[i + 1], sellPrice - prices[i]);}for (int i = 0; i < n; i++)profit = max(profit, p1[i] + p2[i]);return profit;}






0 0