zoukankan      html  css  js  c++  java
  • LeetCode 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).

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         if (prices.length<=1) {
     4             return 0;
     5         }
     6 
     7         int[] left = new int[prices.length];
     8         int[] right = new int[prices.length];
     9         int min = prices[0];
    10         for (int i = 1; i < prices.length; i++) {
    11             left[i] = left[i - 1] > prices[i] - min ? left[i - 1] : prices[i] - min;
    12             min = min < prices[i] ? min : prices[i];
    13         }
    14 
    15         int max = prices[prices.length - 1];
    16         for (int i = prices.length - 2; i >= 0; i--) {
    17             right[i] = right[i + 1] > max - prices[i] ? right[i + 1] : max - prices[i];
    18             max = max > prices[i] ? max : prices[i];
    19         }
    20         int sum = Integer.MIN_VALUE;
    21         for (int i = 0; i < left.length; i++) {
    22             sum = sum > left[i] + right[i] ? sum : left[i] + right[i];
    23         }
    24         return sum;
    25     }
    26 }
  • 相关阅读:
    Windows解决端口占用
    Oracle数字格式化
    Windows生成项目目录结构
    IDEA激活教程
    Windows搭建SMB服务
    在右键新建菜单中添加新项目
    Fastjson1.2.47反序列化+环境搭建+漏洞复现
    nmap常用命令及端口
    Shiro反序列化复现
    CVE-2020-0796漏洞复现
  • 原文地址:https://www.cnblogs.com/birdhack/p/4156599.html
Copyright © 2011-2022 走看看