[LeetCode]Best Time to Buy and Sell Stock II

it2025-06-16  18

题目:给定一个整形数组,表示股票走势,股票能够买入卖出随意次。求能够攒到的最大利润

算法:相当于对股票上升走势求和

比如:股票走势:1,1,3,2,5,7,1,3,2,0。则最大利润为(3-1)+(5-2)+(7-5)+(3-1)=9

public class Solution { public int maxProfit(int[] prices) { if (0 == prices.length) { // Empty array return 0; } int maxProfile = 0; int sellIn = prices[0]; for (int i=1; i<prices.length; ++i) { if (prices[i] > sellIn) { maxProfile += (prices[i]-sellIn); sellIn = prices[i]; } else { sellIn = prices[i]; } } return maxProfile; } }

转载于:https://www.cnblogs.com/bhlsheji/p/5151283.html

相关资源:数据结构—成绩单生成器
最新回复(0)