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 }
  • 相关阅读:
    一些名词的解释
    开源代码从哪里获取
    Joomla软件及其类似物
    js常用随手记
    常用且难记的一些css
    阿里云ecs使用补充说明
    那些年踩过的坑之移动端
    一个题目引发的闭包、函数声明以及作用域的简单思考
    浅析toString()和toLocaleString()的区别
    由[]==![]说开去
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4825119.html
Copyright © 2011-2022 走看看