zoukankan      html  css  js  c++  java
  • LeetCode OJ

    题目:

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

    解题思路:

    遇到price[i] < price[i-1] ,则将前一段时间的收益加上。注意处理末尾元素。

    代码:

    class Solution {
    public:
        int maxProfit(vector<int> &prices) {
            if (prices.size() == 0) {
                return 0;
            }
            int lower = 0, higher = 0;
            int ans = 0;
    
            for (int i = 1; i < prices.size(); i++){
                if (prices[i] >= prices[higher]){
                    higher++;
                }
                else {
                    ans += (prices[higher] - prices[lower]);
                    lower = i;
                    higher = i;
                }
            }
            if (prices[prices.size()-1] > prices[lower]) {
                ans += (prices[prices.size() - 1] - prices[lower]);
            }
            return ans;
    
        }
    };
  • 相关阅读:
    iOS9 HTTP 不能正常使用的解决办法
    IOS UIWebView的一些用法总结
    顺序查找
    循环队列
    队列的链式存储实现
    栈的链式存储实现
    顺序表的实现
    MessageBox函数
    二分法查找
    冒泡排序
  • 原文地址:https://www.cnblogs.com/dongguangqing/p/3727819.html
Copyright © 2011-2022 走看看