zoukankan      html  css  js  c++  java
  • 123. Best Time to Buy and Sell Stock III ~~

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

    这道题要求我们最多做两笔交易,求其最大利润。此题是DP题目,需要写出状态方程,即profit = transaction(1)+transaction(2)=sell(1)-buy(1)+sell(2)-buy(2)。代码如下:

    public class Solution {

        public int maxProfit(int[] prices) {

            int buy1 = Integer.MIN_VALUE;

            int buy2 = Integer.MIN_VALUE;

            int sell1 = 0;

            int sell2 = 0;

            for(int i=0;i<prices.length;i++){

                buy1 = Math.max(buy1,-prices[i]);

                sell1 = Math.max(sell1,prices[i]+buy1);

                buy2 = Math.max(buy2,sell1-prices[i]);

                sell2 = Math.max(sell2,buy2+prices[i]);

            }

            return sell2;

        }

    }

  • 相关阅读:
    iOS 之 创建分类
    iOS 之 动画
    iOS 倒出spa文件 打包
    js闭包
    wampserver配置多站点
    js重定向
    php obstart
    php保存远程图片
    php获取前天的昨天的日期
    weixin js接口
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6358634.html
Copyright © 2011-2022 走看看