122. Best Time to Buy and Sell Stock II

来源:互联网 发布:cs1.5弹道优化脚本 编辑:程序博客网 时间:2024/05/16 07:58

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

(转)考虑如果是我们在炒股,那么我们在某天买入股票的时候,如果明天比今天价格高,那么卖给明天是赚的,如果后天更高,那肯定会想等到后天,也就是会一直等到连续的最高的那一天,而反过来想,每天都卖其实跟等到那天卖是一样的,对吧,只要今天比昨天价格高,那就昨天买,今天卖,反正又不要手续费。

https://leetcode.com/discuss/42176/three-lines-in-c-with-explanation

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


0 0
原创粉丝点击