zoukankan      html  css  js  c++  java
  • Best Time to Buy and Sell Stock II 解答

    Question

    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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times). However, you may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

    Solution

    The key to this problem is to only consider local minimizer point and local maximizer point. And then add up sums. In this way, we avoid processing situation that transactions happen on one day.

     1 public class Solution {
     2     public int maxProfit(int[] prices) {
     3         if (prices == null || prices.length < 2)
     4             return 0;
     5         int result = 0, localMin = prices[0], localMax = prices[0], i = 0, length = prices.length;
     6         while (i < length) {
     7             // To find local minimizer point
     8             while (i < length - 1 && prices[i + 1] < prices[i])
     9                 i++;
    10             localMin = prices[i];
    11             
    12             // To find local maximizer point
    13             i++;
    14             if (i == length) {
    15                 localMax = prices[length - 1];
    16             } else {
    17                 while (i < length - 1 && prices[i + 1] > prices[i])
    18                     i++;
    19                 if (i < length - 1)
    20                     localMax = prices[i];
    21                 else if (i == length - 1)
    22                     localMax = prices[length - 1];
    23             }
    24             result += (localMax - localMin);
    25         }
    26         return result;
    27     }
    28 }
  • 相关阅读:
    284.软件体系结构集成开发环境的作用
    Socket编程:邮件客户
    Socket编程:UDP Ping
    Socket编程:Web服务器
    计算机网络面试题总结(网络层)
    零基础黑客入门
    MYSQL的安装和配置(Windows)
    计算机网络面试题(分层概念+数据链路层)
    车载网络入侵检测系统设计
    操作系统知识点
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4825119.html
Copyright © 2011-2022 走看看