LeetCode-Best Time to Buy and Sell Stock II-解题报告

来源:互联网 发布:linux libx264 编辑:程序博客网 时间:2024/05/17 17:40

原题链接https://leetcode.com/problems/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 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).


和best-time-to-buy-and-sell-stock相比 少了一个条件限制,就是你可交易你想交易的次数。


和一用相同的方法,用p[i] = nums[i] - nums[i-1],相比1就更简单了,直接将p[i]大于等于0的全部加起来就行了,当然不加为0也是ok的。


<span style="font-size:14px;">class Solution {public:    int maxProfit(vector<int>& prices) {if (prices.size() < 2)return 0;for (int i = 1; i < prices.size(); ++i)prices[i - 1] = prices[i] - prices[i - 1];int ans = 0;for (int i = 0; i < prices.size() - 1; ++i){if (prices[i] < 0)continue;ans += prices[i];}return ans;}};</span>


0 0
原创粉丝点击