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

    我觉得这个就是贪心。对于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;
        }
    };
  • 相关阅读:
    idea创建Javaweb项目
    装配bean,基于xml
    IoC(控制反转)和DI(依赖注入)
    jar包介绍
    使用的基本方法
    struts2的常量
    jar包
    调用函数,模块
    Vue中的指令(听博主说总结的很好)
    React的核心概念
  • 原文地址:https://www.cnblogs.com/pk28/p/7229486.html
Copyright © 2011-2022 走看看