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 }
  • 相关阅读:
    <JZOJ5912>VanUSee
    <JZOJ5910>duliu
    <JZOJ5913>林下风气
    pytest学习笔记(二)
    试用saucelabs进行浏览器兼容性测试
    pytest学习笔记(一)
    SSM框架搭建,以及mybatis学习
    游戏2048的python实现
    使用svn在github上下载文件夹
    jenkins集成python的单元测试
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4825119.html
Copyright © 2011-2022 走看看