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

    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).

    最好用栈来想问题, 当前元素比栈内元素大 或小的时候怎么办, 最后优化成单个变量, 数组的题除了常用动归, 也常用栈, 用动归前看看解决了重复计算问题吗? 得想出状态转移方程来, 不然就不是动归

    public int maxProfit(int[] prices) {
            int ans = 0;
            
            int n = prices.length;
            if (n == 0 || prices == null) {
                return ans;
            }
            int min = prices[0];
            for (int i = 1; i < n; i++) {
                if (prices[i] > min) {
                    ans += prices[i] - min;
                    
                }
                min = prices[i];
            }
            return ans;
        }
    }
    

      

  • 相关阅读:
    [HNOI 2003] 消防局的设立
    Codeforces 341
    CF 专栏
    TC SRM 570
    TC SRM 588
    TC SRM 589
    TC专栏
    BZOJ 第二十一页 除草
    BZOJ 第二十二页 除草
    BZOJ 第二十三页 除草
  • 原文地址:https://www.cnblogs.com/apanda009/p/7281977.html
Copyright © 2011-2022 走看看