zoukankan      html  css  js  c++  java
  • LeetCode Best Time to Buy and Sell Stock II

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int len = prices.size();
            if (len < 1) return 0;
            int sum = 0;
            int last_low = prices[0];
    
            bool increasing = false;
            for (int i=1; i<len; i++) {
                int cur = prices[i];
                if (cur < prices[i - 1]) {
                    if (increasing) {
                        increasing = false;
                        sum += prices[i - 1] - last_low;
                    }
                    last_low = cur;
                } else {
                    if (increasing) {
                        
                    } else {
                        increasing = true;
                    }
                }
            }
            if (increasing) {
                sum += prices[len-1] - last_low;
            }
            return sum;
        }
    };

     第二轮:

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

    看看当初写的有点繁琐啊

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            int len = prices.size();
            if (len < 2) return 0;
            int last = prices[0];
            int profit = 0;
            for (int i=1; i<len; i++) {
                profit += max(0, prices[i] - last);
                last = prices[i];
            }
            return profit;
        }
    };
  • 相关阅读:
    JSDI——实现数据库连接池(JDBC改进)
    MD5加密算法(实际应用)
    Java Web 自动登录
    异步编程设计模式Demo
    异步编程设计模式Demo
    禁止程序启动2次
    C#线程同步的几种方法
    ASP.NET MVC的Action Filter
    带有返回值的intent
    android 属性动画
  • 原文地址:https://www.cnblogs.com/lailailai/p/3805289.html
Copyright © 2011-2022 走看看