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

    我觉得这个就是贪心。对于prices[i] 往后找最后的prices[j] 然后把这段差值加上... 对于这种情况 1 5 5 10 当然取1买 10卖

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            int x = 0,ans = 0;
            int n = prices.size();
            if (n <= 1) return 0;
            int be = 0;
            x = prices[be];
            for (int i = 0; i < n; ++i) {
                if (prices[i] >= x) {
                    x = prices[i];
                }
                else {
                    ans += x - prices[be];
                    be = i;
                    if (be < n)x = prices[be];
                }
            }
            if (x - prices[be] > 0) ans += x - prices[be];
            return ans;
        }
    };
  • 相关阅读:
    Hibernate之二级缓存
    Hibernate之HQL
    Hibernate 一对多自关联 多对多
    hibernate关联关系(一对多)
    Hibernate之主键生成策略
    Hibernate01
    struts的图片上传
    HashMap和HashTable本质性的区别
    集合03
    集合
  • 原文地址:https://www.cnblogs.com/pk28/p/7229486.html
Copyright © 2020-2023  润新知