欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Best Time to Buy and Sell Stock II

程序员文章站 2022-05-21 13:23:43
...
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).

与第一个股票问题的区别是这里我们可以进行多次交易,我们同样用两个变量,profit用来记录当前交易是否盈利,如果是盈利就加入到总利润max中,如果亏损就继续往下查找。这样只要能盈利的都会记录到max中,代码如下:
public class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        int max = 0;
        for(int i = 1; i < prices.length; i++) {
            profit = prices[i] - prices[i - 1];
            if(profit > 0) 
                max += profit;
        }
        return max;
    }
}
相关标签: 动态规划 股票