LeetCode122. Best Time to Buy and Sell Stock II

来源:互联网 发布:智能电视机网络电视机 编辑:程序博客网 时间:2024/05/28 04:55

这两周开始接触贪心算法,顾名思义就是使其利益最大化了。先选一道最简单的相关题目来练练手。

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

意思即是:假设有一个数组,它的第i个元素是一个给定的股票在第i天的价格。设计一个算法来找到最大的利润。你可以完成尽可能多的交易(多次买卖股票)。然而,你不能同时参与多个交易(你必须在再次购买前出售股票)。

其实思路很简单,要事利益最大化,那便是不能放过每个可以赚到money的机会。只要相间的两次股票有可以赚的差价,那就把它放入利润当中。

代码如下:


class Solution {public:    int maxProfit(vector<int> &prices) {        int l = prices.size();        if(l == 0) return 0;                    int money = 0;        int buy = prices[0];        int last = prices[0];        for(int i = 1; i < l; i ++)        {            if(prices[i] < last)            {                money += (last - buy);                buy = prices[i];            }            last = prices[i];        }        money += (last - buy);        return money;    }};


原创粉丝点击