LeetCode题目:122. Best Time to Buy and Sell Stock II

来源:互联网 发布:custom.js 编辑:程序博客网 时间:2024/05/18 03:23

题目原址:点击打开链接  

题目描述:

Say you have an array for which the ith element is the price of a given stock on dayi.

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 l=prices.size();        if(l<=1)return 0;        int b=prices[0],m=prices[0],sum=0;        for(int i=0;i<l;i++){            if(prices[i]>=m){                m=prices[i];            }            if(prices[i]<m){                sum+=m-b;                b=prices[i];                m=prices[i];            }            if(i==l-1&&prices[i]>=m){                sum+=(m-b);                b=prices[i];                m=prices[i];            }        }        return sum;    }};

0 0
原创粉丝点击