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天的股票价格,你可以在这个数组内买卖多次股票,但手里只能有一只股票,比如说5,0,1,2,3,4你可以买0卖了0再买1,卖了1再买2...
前一天买,后一天卖,如果有钱赚,加到pro中,最后返回pro
1 public class Solution { 2 public int maxProfit(int[] prices) { 3 int pro = 0; 4 for(int i = 1; i < prices.length; i++){ 5 if(prices[i] - prices[i - 1] > 0) 6 pro = pro + prices[i] - prices[i - 1]; 7 } 8 9 return pro; 10 } 11 }