zoukankan      html  css  js  c++  java
  • leetcode -- Best Time to Buy and Sell Stock III TODO

    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         // Start typing your Java solution below
     4         // DO NOT write main() function
     5         if(prices.length == 0){
     6             return 0;
     7         }
     8         int result = Integer.MIN_VALUE;
     9         int[] profits = new int[prices.length];
    10         int min = Integer.MAX_VALUE, maxBeforeI = Integer.MIN_VALUE;
    11         for (int i = 0; i < prices.length; i++) {
    12             if (prices[i] < min) {
    13                 min = prices[i];
    14             }
    15             if (prices[i] - min > maxBeforeI) {
    16                 maxBeforeI = prices[i] - min;
    17             }
    18             profits[i] = maxBeforeI;
    19         }
    20         int max = Integer.MIN_VALUE;
    21         for (int i = prices.length - 1; i >= 0; i--) {
    22             if (prices[i] > max) {
    23                 max = prices[i];
    24             }
    25 
    26             int profit = max - prices[i];
    27 
    28             if (profit + profits[i] > result) {
    29                 result = profit + profits[i];
    30             }
    31         }
    32         return result;
    33     }
    34 }

    m transactions solution not understand

    http://discuss.leetcode.com/questions/287/best-time-to-buy-and-sell-stock-iii

  • 相关阅读:
    html笔记
    Git入门学习总结
    使用OpenSSH远程管理Linux服务器
    Linux 网卡驱动的安装
    vi的使用
    Linux下常用的数据恢复工具
    网络文件系统(NFS)的使用
    文件系统管理
    磁盘存储管理
    用户权限管理
  • 原文地址:https://www.cnblogs.com/feiling/p/3265090.html
Copyright © 2011-2022 走看看