zoukankan      html  css  js  c++  java
  • 【LeetCode】122. Best Time to Buy and Sell Stock II

    Difficulty:easy

     More:【目录】LeetCode Java实现

    Description

    https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

    Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

    Note: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

    Example 1:

    Input: [7,1,5,3,6,4]
    Output: 7
    Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
                 Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
    

    Example 2:

    Input: [1,2,3,4,5]
    Output: 4
    Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
                 Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
                 engaging multiple transactions at the same time. You must sell before buying again.
    

    Example 3:

    Input: [7,6,4,3,1]
    Output: 0
    Explanation: In this case, no transaction is done, i.e. max profit = 0.

    Intuition

    Normal Method: Find the peak and valley

    Clever Method: If there is profit between two days, make a deal.

    Solution

        //Normal Method: Find the peak and valley
        public int maxProfit1(int[] prices) {
            if(prices==null || prices.length<=1)
                return 0;
            int i=0,j=0;
            int profit=0;
            while(i<prices.length && j<prices.length){
                while(i+1<prices.length && prices[i+1]<prices[i])
                    i++;
                j=i+1;
                if(j==prices.length)
                    break;
                else{
                    while(j+1<prices.length && prices[j+1]>prices[j])
                        j++;
                }
                profit+=prices[j]-prices[i];
                i=j+1; //don't forget this line
            }
            return profit;
        }
        
        //Clever Method
         public int maxProfit(int[] prices) {
             if(prices==null || prices.length<=1)
                return 0;
             int profit=0;
             for(int i=0; i<prices.length-1; i++){
                 if(prices[i+1]>prices[i])
                     profit+=prices[i+1]-prices[i];
             }
             return profit;
         }
    

      

    Complexity

    Time complexity : O(n)

    Space complexity : O(1)

     

     More:【目录】LeetCode Java实现

  • 相关阅读:
    ubnt+ros 接入无线
    生成new, old的 shell script
    lua学习记录
    反编译dtsi
    抓包软件PowerSniff开发计划
    android的ArrayMap类
    京东买的5本书
    c++ 变量必须初始化吗???
    cocos2dx 很好的源码分析博文
    cocos2dx 最基本,纯色、字体、图片
  • 原文地址:https://www.cnblogs.com/yongh/p/11636006.html
Copyright © 2011-2022 走看看