diff options
-rw-r--r-- | best_time_buy_sell_stock3.c | 44 | ||||
-rw-r--r-- | best_time_buy_sell_stock3.py | 35 |
2 files changed, 79 insertions, 0 deletions
diff --git a/best_time_buy_sell_stock3.c b/best_time_buy_sell_stock3.c new file mode 100644 index 0000000..8867f7b --- /dev/null +++ b/best_time_buy_sell_stock3.c @@ -0,0 +1,44 @@ +// 123. Best Time to Buy and Sell Stock III +#include "leetcode.h" + +/* + * you are given an array 'prices' where 'prices[i]' is the price of a given + * stock on the i'th day. find the maximum profit you can achieve. you may + * complete at most two transactions. note, you may not engage in multiple + * transactions simultaneously. + */ + +int maxProfit(int *prices, int pricesSize) { + int *s1 = (int *)calloc(pricesSize, sizeof(int)); + int *s2 = (int *)calloc(pricesSize, sizeof(int)); + int max = INT_MIN, min = prices[0]; + for (int i = 1; i < pricesSize - 1; i++) { + if (min > prices[i]) + min = prices[i]; + if (max < prices[i] - min) + max = prices[i] - min; + s1[i] = max; + } + min = INT_MIN, max = prices[pricesSize - 1]; + s2[pricesSize - 1] = 0; + for (int i = pricesSize - 2; i >= 0; i--) { + if (prices[i] > max) + max = prices[i]; + if (min < max - prices[i]) + min = max - prices[i]; + s2[i] = min; + } + max = INT_MIN; + for (int i = 0; i < pricesSize; i++) + max = max < s1[i] + s2[i] ? s1[i] + s2[i] : max; + free(s1), free(s2); + return max; +} + +int main() { + int p1[] = {3, 3, 5, 0, 0, 3, 1, 4}, p2[] = {1, 2, 3, 4, 5}, + p3[] = {7, 6, 4, 3, 1}; + printf("%d\n", maxProfit(p1, ARRAY_SIZE(p1))); // expect: 6 + printf("%d\n", maxProfit(p2, ARRAY_SIZE(p2))); // expect: 4 + printf("%d\n", maxProfit(p3, ARRAY_SIZE(p3))); // expect: 0 +} diff --git a/best_time_buy_sell_stock3.py b/best_time_buy_sell_stock3.py new file mode 100644 index 0000000..01fc2b3 --- /dev/null +++ b/best_time_buy_sell_stock3.py @@ -0,0 +1,35 @@ +# 123. Best Time to Buy and Sell Stock III + +""" +you are given an array 'prices' where 'prices[i]' is the price of a given +stock on the i'th day. find the maximum profit you can achieve. you may +complete at most two transactions. note, you may not engage in multiple +transactions simultaneously. +""" + + +class Solution(object): + def maxProfit(self, prices): + """ + :type prices: List[int] + :rtype: int + """ + if len(prices) == 0: + return 0 + k = 2 + states = [0] + [-float("inf") for i in range(k * 2)] + states[1] = -prices[0] + for i in range(1, len(prices)): + for j in range(k): + states[2 * j + 1] = max(states[2 * j + 1], states[2 * j] - prices[i]) + states[2 * j + 2] = max( + states[2 * j + 2], states[2 * j + 1] + prices[i] + ) + return max(0, states[-1]) + + +if __name__ == "__main__": + obj = Solution() + print(obj.maxProfit(prices=[3, 3, 5, 0, 0, 3, 1, 4])) + print(obj.maxProfit(prices=[1, 2, 3, 4, 5])) + print(obj.maxProfit(prices=[7, 6, 4, 3, 1])) |