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;
        }
    };


  • 相关阅读:
    记账本开发第一天-补
    20200418-补
    20200411-补
    20200404-补
    20200328-补
    暴力解N皇后
    nN皇后递归
    Hanoi汉诺塔非递归栈解
    Hanoi汉诺塔递归
    JMMjmm模型
  • 原文地址:https://www.cnblogs.com/jsrgfjz/p/8519898.html
Copyright © 2011-2022 走看看