LeetCode - 121-123 Best Time to Buy and Sell Stock

作者 QIFAN 日期 2016-07-18
LeetCode - 121-123 Best Time to Buy and Sell Stock

121. Best Time to Buy and Sell Stock

Difficulty: Easy
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.

思路

代码

public class Solution {
public int maxProfit(int[] prices) {
int maxprice = 0;
int maxday = 0;
for(int i=0; i<prices.length; i++) {
if(prices[i]>maxprice) {
maxprice = prices[i];
maxday = i;
}
}
if(maxday==0) return 0;
int minprice = maxprice;
for(int i=0; i<maxday; i++) {
minprice = prices[i]<minprice?prices[i]:minprice;
}
return maxprice - minprice;
}
}

122. Best Time to Buy and Sell Stock II

Difficulty: Medium

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

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).

思路

代码

public class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length<2) return 0;
int sum = 0;
for(int i=1; i<prices.length; i++) {
sum += prices[i]-prices[i-1]>0 ? prices[i]-prices[i-1] : 0;
}
return sum;
}
}

123. Best Time to Buy and Sell Stock III

Difficulty: Hard

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

Design an algorithm to find the maximum profit. You may complete at most two transactions.

思路

代码

public class Solution {
public int maxProfit(int[] prices) {
if(prices==null || prices.length<2) return 0;
// (0, i)里最大的sum
int[] forward = new int[prices.length];
forward[0] = 0;
int min = prices[0];
for(int i=1; i<forward.length; i++) {
min = prices[i]<min ? prices[i] : min;
forward[i] = max(prices[i]-min, forward[i-1]);
}
// (i, prices.length)里最大的sum
int[] backward = new int[prices.length];
int max = prices[prices.length-1];
for(int i=prices.length-2; i>=0; i--) {
max = max(prices[i], max);
backward[i] = max(max-prices[i], backward[i+1]);
}
max = 0;
for(int i=0; i<prices.length; i++) {
max = max(max, forward[i]+backward[i]);
}
return max;
}
public int max(int a, int b) {
return a>b?a:b;
}
}

原题链接:
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii/