LeetCode 122. Best Time to Buy and Sell Stock II (Easy)

来源:互联网 发布:中银淘宝信用卡查询 编辑:程序博客网 时间:2024/06/10 05:53

题目描述:

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

题目大意:给一个数组,第i个元素代表第i天一只股票的价格,可以任何时候自由买进卖出,算出最大利润。

思路:贪心算法,如果第i+1天的股票价格比第i天的股票高,说明有利润,那就买进卖出,把所有利润加起来即可。

c++代码:

class Solution {public:    int maxProfit(vector<int>& prices) {        int ans = 0;        int length = prices.size() - 1;        for (int i = 0; i < length; i++)        {            if (prices[i + 1] > prices[i])            {                ans += prices[i + 1] - prices[i];            }        }        return ans;    }};
原创粉丝点击