zoukankan      html  css  js  c++  java
  • 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).


    思路:贪心

    贪心算法,只要我当前价格比之前的高,那我就卖了,我可以再买。后期我再买,用一个sum的全局变量。

    代码:

    class Solution {
    public:
        int maxProfit(vector<int>& prices) {
            //贪心法,只要后面一天比前面一天价格高,就卖。然后再买。
            //最简单的算法
            if(prices.empty()){
                return 0;
            }
            
            int sum=0;
            for(int i=1;i<=prices.size()-1;i++){
                if(prices[i]>prices[i-1]){
                    sum=sum+prices[i]-prices[i-1];
                }
            }
            
            return sum;
        }
    };


  • 相关阅读:
    Vue状态管理
    Vue延迟点击
    Vue路由
    简单的队列应用
    Uncaught SyntaxError: Unexpected token )
    视频转码
    判断是否为视频文件
    Press ^C at any time to quit.
    Node.js学习
    YUM安装LAMP与LNMP
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519898.html
Copyright © 2011-2022 走看看