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

      

  • 相关阅读:
    博客最新博文通告
    博文快速导航
    创业
    央行回应中国版数字货币:与人民币等价 不会让钱贬值
    高屋建瓴
    高层人对事的处理
    老板的区别
    沟通的四大法则
    赚钱规则
    合伙做生意的原则
  • 原文地址:https://www.cnblogs.com/apanda009/p/7281977.html
Copyright © 2011-2022 走看看