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;
        }
    }
    

      

  • 相关阅读:
    Python大婶博客汇总
    DevOps之零停机部署
    DevOps之持续交付
    DevOps工具链
    DevOps的概念
    敏捷开发
    自动化运维
    tomcat优化
    java 集合专练
    java匿名内部类,多态,接口练习
  • 原文地址:https://www.cnblogs.com/apanda009/p/7281977.html
Copyright © 2011-2022 走看看