【leetcode】123. Best Time to Buy and Sell Stock III【java】

来源:互联网 发布:数字音频媒体矩阵 编辑:程序博客网 时间:2024/06/16 11:22

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.

Note:
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) {        int buy1 = Integer.MAX_VALUE;        int buy2 = Integer.MIN_VALUE;        int sell1 = 0;        int sell2 = 0;        for (int price : prices){            buy1 = Math.min(buy1, price);            sell1 = Math.max(sell1, price - buy1);            buy2 = Math.max(buy2, sell1 - price);            sell2 = Math.max(sell2, price + buy2);        }        return sell2;    }}


0 0
原创粉丝点击