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

      

  • 相关阅读:
    C++学习笔记32:泛型编程拓展1
    C++学习笔记31:术语翻译
    Sqrt(x)
    Search a 2D Matrix
    Pascal's Triangle II
    Pascal's Triangle
    Climbing Stairs
    Linux实用命令
    Binary Tree Inorder Traversal
    Minimum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/apanda009/p/7281977.html
Copyright © 2011-2022 走看看